C# 检查xml节点是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12004903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 20:03:23  来源:igfitidea点击:

Check xml node is exist or not?

c#asp.netxml

提问by Shree

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

我想检查给定的节点是否存在于*.xml文件中。我尝试:

 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 xmlfile I haven't node called languageSo its gives a Null Reference Ex... How to check Given node is exist or not in *.xmlfile? Thanks.

但我认为它只检查节点值。在一些xml文件中我没有节点调用language所以它给出了一个 Null Reference Ex... 如何检查给定节点是否存在于*.xml文件中?谢谢。

采纳答案by weston

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

东西是null。您正在检查所选的“语言”节点null,它node本身也是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.

使用变量,例如一个 fornode.SelectSingleNode("language")这样你就不会这样做两次。这将帮助您找到错误。

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