Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check xml node is exist or not?

Tags:

c#

xml

asp.net

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.

like image 874
4b0 Avatar asked Feb 20 '23 11:02

4b0


1 Answers

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;
    }
  }
}
like image 70
weston Avatar answered Feb 22 '23 00:02

weston