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;
}
}