1

考虑以下 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 语法是什么?

4

3 回答 3

2

你错过了负载

var xmlDoc = new XmlDocument();
xmlDoc.Load(path);
Console.WriteLine(xmlDoc.SelectSingleNode("/SomeRoot/SomeElement/SomeThing[../SomeOther='Cat']").InnerText);
于 2012-08-31T08:13:34.007 回答
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;
于 2012-08-31T08:10:41.517 回答
1

您可以避免使用任何反向轴

/*/SomeElement[SomeOther='Cat']/SomeThing
于 2012-08-31T12:53:42.793 回答