1

I'm still getting comfortable working with XML files. I've been looking at a number of examples online and have been struck by the lack of error handling.

The most common error is something like el.Attributes["name"].Value. Since XML is human-editable, it's possible that the attribute is missing. And trying to reference the Value property on null will raise an exception. Other issues would be related to data not being in the expected format.

So I started writing some helper extension methods along the lines of the following:

public static class XmlHelpers
{
    public static string GetValue(this XmlAttribute attr, string defaultValue = "")
    {
        if (attr != null)
            return attr.Value;
        return defaultValue;
    }

    public static bool GetValueBool(this XmlAttribute attr, bool defaultValue = false)
    {
        bool value;
        if (bool.TryParse(attr.GetValue(), out value))
            return value;
        return defaultValue;
    }
}

I know this will work. But am I missing anything? Does XmlDocument already provide functionality that makes this type of stuff unnecessary? I'm just wondering how others are dealing with this.

I realize that many XML files are never edited by humans. And, for that reason, many people may just write code that assumes there will be no errors. If there is an error, then there's an exception. I can understand that. But I was hoping to give my app a little more flexibility if the files are edited by humans, and something isn't formatted quite right.

4
  • 1
    If you're comfortable with LINQ, I'd suggest moving to LINQ to XML (though you'd still have the same challenges with missing elements/attributes or misspelled names). Commented Jun 30, 2013 at 18:10
  • If it doesn't take care of these issues, why do you suggestion moving to LINQ to XML? Commented Jun 30, 2013 at 18:13
  • It's a lot easier (IMO) then using XmlDocument is the main reason. You can parse, modify and create XML documents with a few lines of code. Commented Jun 30, 2013 at 18:18
  • Also, both XmlDocument and XDocument have a Validate method that will validate the document against a specified schema. That would let you know before you start working with it whether or not there are any errors in it (if you have a schema). Commented Jun 30, 2013 at 18:26

2 Answers 2

1

Depending on what errors you're interested in accommodating (and what the XML you're parsing looks like), the XmlSerializer class might be of use:

void Main()
{
    var xmlSerializer = new XmlSerializer(typeof(Foo));
    var foo1 = (Foo)xmlSerializer.Deserialize(new StringReader(@"<Foo a=""11""></Foo>"));
    Console.WriteLine(foo1.A); // 11

    var foo2 = (Foo)xmlSerializer.Deserialize(new StringReader(@"<Foo></Foo>"));
    Console.WriteLine(foo2.A); // 10 (fell back to the default)

    // throws format exception
    var foo3 = (Foo)xmlSerializer.Deserialize(new StringReader(@"<Foo a=""x""></Foo>"));
}

// Define other methods and classes here
[XmlRoot("Foo")]
public class Foo {
    public Foo() { this.A = 10; }

    [XmlAttribute("a")]
    public int A { get; set; }
}

Handling parsing errors is obviously more difficult. One way could be to use XmlSerializer as described above but use string for all types (perhaps with wrapper properties that incorporate the handling of bad formatting). To get more type-safety, you could define custom types that implement IXmlSerializable "safely" and which define implicit conversions to a System type.

Sign up to request clarification or add additional context in comments.

Comments

0

You're not really talking about "errors" here, you're talking about things that can legitimately happen. XML is a very flexible format. One of the problems is that conventional programming languages are far less flexible.

The kind of flexibility you are looking for is built into XML-oriented languages like XPath, XQuery, and XSLT. Low-level programming against DOM interfaces is really hard work compared with XPath, for the reasons you are discovering.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.