考虑以下XML:
<SomeRoot>
<SomeElement>
<SomeThing>25</SomeThing>
<SomeOther>Cat</SomeOther>
</SomeElement>
<SomeElement>
<SomeThing>46</SomeThing>
<SomeOther>Dog</SomeOther>
</SomeElement>
<SomeElement>
<SomeThing>83</SomeThing>
<SomeOther>Bat</SomeOther>
</SomeElement>
<SomethingElse>Unrelated to the SomeElements above</SomethingElse>
</SomeRoot>
我想select SomeThing where SomeOther = 'Cat'
。以下C#代码抛出空引用异常:
xmlDoc = new XmlDocument();
this.path = path;
// Path is passed elsewhere
Console.WriteLine(xmlDoc.SelectSingleNode("/SomeRoot/SomeElement/SomeThing[../SomeOther='Cat']").InnerText);
这里使用的正确XPath语法是什么?
答案 0 :(得分:2)
您缺少负载
var xmlDoc = new XmlDocument();
xmlDoc.Load(path);
Console.WriteLine(xmlDoc.SelectSingleNode("/SomeRoot/SomeElement/SomeThing[../SomeOther='Cat']").InnerText);
答案 1 :(得分:1)
这就是我所做的并且有效;
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(@"<SomeRoot><SomeElement><SomeThing>25</SomeThing><SomeOther>Cat</SomeOther></SomeElement></SomeRoot>");
var x = xDoc.SelectSingleNode("/SomeRoot/SomeElement/SomeThing[../SomeOther= 'Cat']").InnerText;
答案 2 :(得分:1)
您可以避免使用任何反转轴:
/*/SomeElement[SomeOther='Cat']/SomeThing