Search code examples
xmllanguage-agnosticconfigurationmagic-numbers

What to do with XML node names (hard coded values)?


I've been working with xml lately. And have noticed a bit of a phenomenon (maybe not that big of a deal to the rest of the world, but to me it was). Perhaps, it is me being a newb. But shouldn't most hard coded or magic numbers be broken out to a configuration file? For example,

    string url = "http://www.domain.com/aDocument.xml";        
    XmlDocument feed = new XmlDocument();
    feed.Load(url);

    XmlNode errorsNode = feed.SelectSingleNode("Errors");

    if (errorsNode != null)
    {
        XmlNode error = errorsNode.FirstChild;
        lblError.Text = "Error: " + error.SelectSingleNode("Code").InnerText;
    }

Here is the xml document:

  <Errors>
    <Error>
        <Code>AWS.MissingParameters</Code>
        <Message>You are missing an parameter</Message>
    </Error>
 </Errors>

How would you parse this without hardcoding "code" or "message"?


Solution

  • Same as I would for numbers. I'd declare constants of type string which have the name of the element to get, and then pass that to the methods on my XML tools.

    However, you might want to consider creating an object representation from the XML document (or schema if you have it) which would handle all of this for you. This way, you can just load up the XML document into the code, and it will do the parsing for you into an object representation.

    Then, if the XML changes, you would modify the generated code to use your new element names.

    You want to use the XSD.EXE tool for this.