XmlDocument.Load Error Handling
From one of the projects I have been working on, I came across a snippet of code that used the XmlDocument.Load method. What alarmed me about this piece of code was the fact that there was no error handling. If for some reason the XML file could not be found or a node was missing, the whole page would have crashed. Not good.
I must admit, I am not exactly the best person to speak about implementing wide-scale error handling in every facet of code. But I do ensure the core foundations of an application or website do incorporate sufficient error handling.
So back to the matter in hand. This is the original code using the XmlDocument.Load functionality:
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("/xml/storeGB.xml"));
XmlNode countryNode = doc.SelectSingleNode("//countries");
foreach (XmlNode node in countryNode.ChildNodes)
{
//Do something with the elements
Response.Write(node.Name + node.InnerText);
}
I changed the code to the following:
XmlDocument doc = new XmlDocument();
//Check if language XML file exists
if (File.Exists(Server.MapPath("/xml/storeGB.xml")))
{
try
{
doc.Load(Server.MapPath("/xml/storeGB.xml"));
XmlNode countryNode = doc.SelectSingleNode("//countries");
if (countryNode != null)
{
foreach (XmlNode node in countryNode.ChildNodes)
{
//Do something with the elements
Response.Write(node.Name + node.InnerText);
}
}
else
{
//Output error message if there is no node
}
}
catch (XmlException ex)
{
Debug.WriteLine(String.Format("XmlException for countries: {0}", ex.Message));
}
}
I am sure you will agree that this is the better approach to using XmlDocument.Load.