4b0
4b0

Reputation: 22323

Check xml node is exist or not?

I want to check given node is exist or not in *.xml file. I try:

 string language = node.SelectSingleNode("language") != null ? (node.SelectSingleNode("language").Value == "en" ? "en-US" : "en-US") : "en-US";

But I think its check only for node value.In some xml file I haven't node called language So its gives a Null Reference Ex... How to check Given node is exist or not in *.xml file? Thanks.

Upvotes: 4

Views: 40835

Answers (1)

weston
weston

Reputation: 54801

Something is null. You are checking the selected "language" node for null, so is node itself null?

Spread the code out over more lines, nested ?: code is not easy to follow and you have had to repeat default values and function calls.

Use variables, such as one for node.SelectSingleNode("language") so you don't do that twice. And this will help you find the bug.

string language = "en-US"; //default
if(node!=null)
{
  var langNode = node.SelectSingleNode("language");
  if(langNode!=null)
  {
    //now look at langNode.Value, and overwrite language variable, maybe you wanted:
    if(langNode.Value != "en")
    {
       language = langNode.Value;
    }
  }
}

Upvotes: 8

Related Questions