Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用xpath从xml文件中选择节点_C#_Xml_Xpath - Fatal编程技术网

C# 使用xpath从xml文件中选择节点

C# 使用xpath从xml文件中选择节点,c#,xml,xpath,C#,Xml,Xpath,我的XML文件如下所示: <?xml version="1.0" encoding="UTF-8"?> <Settings> <SurveySetting IsServeyOn="false" /> </Settings> 但有时我会犯错误。。未找到节点或为空。 是否有其他方法选择节点 XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(filepath); XmlElem

我的XML文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>
   <Settings>
     <SurveySetting IsServeyOn="false" />
   </Settings>
但有时我会犯错误。。未找到节点或为空。
是否有其他方法选择节点

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filepath);
XmlElement root = xmlDoc.DocumentElement;
XmlNode node = root.SelectSingleNode("SurveySetting");
if (node != null && node.Attributes.Count > 0 && node.Attributes["IsServeyOn"] != null && !string.IsNullOrEmpty(node.Attributes["IsServeyOn"].Value))
  {
        RadiobuttonSurverysetting.SelectedValue = node.Attributes["IsServeyOn"].Value;
  }

我已经通过放置一些验证来尝试您的代码,它在我的应用程序中运行良好

还有其他方法,但是您的XPath表达式是有效的,
node
null
表示文档中没有
元素。你绝对确定元素总是存在吗?正如@FrédéricHamidi所说的,在设置RadioButtonServySetting之前,请检查值是否为null。如果它不是null,则设置它。首先用这种方法搜索以避免
null
。。使用
//SurveySetting[not(@IsServeyOn)]
@Babai,你的意思是
//SurveySetting[@IsServeyOn]
,如果元素存在但其属性不存在?@FrédéricHamidi Yes..我的意思是。。
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filepath);
XmlElement root = xmlDoc.DocumentElement;
XmlNode node = root.SelectSingleNode("SurveySetting");
if (node != null && node.Attributes.Count > 0 && node.Attributes["IsServeyOn"] != null && !string.IsNullOrEmpty(node.Attributes["IsServeyOn"].Value))
  {
        RadiobuttonSurverysetting.SelectedValue = node.Attributes["IsServeyOn"].Value;
  }