views:

133

answers:

2

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"?

+2  A: 

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.

casperOne
+2  A: 

I don't know if it's the best option, but I've typically seen this kind of thing handled by using a set of string constants. At least then, if you're processing the same XML schema in multiple places, your magic strings are all defined in one place. I'd think relegating this to a configuration file would be overkill unless the schema changes frequently.

Mike Powell