C# 使用xpath从xml文件中选择节点
我的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 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;
}