if exist on an XML node in XmlNodeList C#

2.1k views Asked by At

How can i check if a node exists in an XmlNodeList? I have populated a list, and i need to query out specific values. this is how I am doing that.

var xList = xelRoot.SelectNodes("aaa/bbb/ccc/ddd/eee/fff/ggg/hhh");
foreach (XmlNode node in xList)
{    
       serviceVal = node["service"].InnerText.ToString(); 
}

there are cases where the service node does not exist. and when that happens I get the error "Object reference is not set to instance of an object".

is there a way to return a string value if the node does not exist?

here is a sample of the xml. notice that rule 1 does not have a service node

<entry name="aaa">
              <from>any</from>
              <to>any</to>
              <source>any</source>
              <destination>any</destination>
              <source-user>any</source-user>
              <category>any</category>
              <service>any</service>
        </entry>
        <entry name="Rule 1">
              <from>any</from>
              <to>any</to>
              <source>any</source>
              <destination>any</destination>
              <source-user>any</source-user>
              <category>any</category>
        </entry>
1

There are 1 answers

2
canon On BEST ANSWER

Simply test for null...

XmlNode subNode;
foreach (XmlNode node in xList)
{    
    subNode = node["service"];
    if (subNode != null)
    {
        serviceVal = subNode.InnerText;
    }
    else 
    {
        serviceVal = string.Empty;
    } 
}