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.
XmlDocumentandXDocumenthave aValidatemethod 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).