XmlDocument.Load Error Handling

Published on
-
1 min read

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.

Before you go...

If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!

Buy Me A Coffee

Leave A Comment

If you have any questions or suggestions, feel free to leave a comment. I do get inundated with messages regarding my posts via LinkedIn and leaving a comment below is a better place to have an open discussion. Your comment will not only help others, but also myself.