Danny Beckett
Danny Beckett

Reputation: 20766

XML SelectSingleNode where sibling = 'something'

Consider the following 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>

I want to select SomeThing where SomeOther = 'Cat'. The following C# code throws a null reference exception:

xmlDoc = new XmlDocument();
this.path = path;
// Path is passed elsewhere

Console.WriteLine(xmlDoc.SelectSingleNode("/SomeRoot/SomeElement/SomeThing[../SomeOther='Cat']").InnerText);

What is the correct XPath syntax to use here?

Upvotes: 1

Views: 2701

Answers (3)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243479

You can avoid using any reverse axis:

/*/SomeElement[SomeOther='Cat']/SomeThing

Upvotes: 1

saj
saj

Reputation: 4796

Here's what I did and it works;

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;

Upvotes: 2

nzjoel
nzjoel

Reputation: 1206

You are missing the load

var xmlDoc = new XmlDocument();
xmlDoc.Load(path);
Console.WriteLine(xmlDoc.SelectSingleNode("/SomeRoot/SomeElement/SomeThing[../SomeOther='Cat']").InnerText);

Upvotes: 3

Related Questions