tags:

views:

34

answers:

2

I am using the following code to retrieve data from the xml file. It is working fine.

Problem: If the node is not available it creating problem. How to check the availability of the node.

ex: some records dose not have description that time it shows Object reference not set to an instance of an object. error.

code:

XmlDocument doc = new XmlDocument();
doc.Load("C:\\Books.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("/NewDataSet/booksdetail");

foreach (XmlNode node in nodes)
{
    string pages = node["pages"].InnerText;
    string description = node["Description"].InnerText; // Error
} 

error: Object reference not set to an instance of an object.

Other option: Working

        string pages = "0";
        string description = "";

        foreach (XmlNode node in nodes)
        {
            foreach(XmlNode childNode in node)
            {
                switch (childNode.Name.ToString())
                {
                    case "pages":
                        pages = node["pages"].InnerText;
                        break;

                    case "Description":
                        description = node["Description"].InnerText;
                        break;
                }
            }
+4  A: 
    XmlDocument doc = new XmlDocument();
    doc.Load("C:\\Books.xml");
    XmlElement root = doc.DocumentElement;
    XmlNodeList nodes = root.SelectNodes("/NewDataSet/booksdetail");

    foreach (XmlNode node in nodes)
    {
        string pages = node["pages"].InnerText;             
        string description = null;
        if(node["Description"]!= null)
        {
           description = node["Description"].InnerText;
        }
    } 
Alex Reitbort
Thank you for your valuable reply.
Geetha
A: 

Check the node for null before retrieving values.

KMan