Search code examples
c#xmlxpathxpathnavigator

Xpath to find first occurrence of two different elements


Using the example below, I would like to use xPath to find the first occurence of two different elements. For example, I want to figure out if b or d appears first. We can obviously tell that b appears before d (looking top-down, and not at the tree level). But, how can I solve this using xpath?

<a>
   <b>
   </b>
</a>
<c>
</c>
<d>
</d>

Right now, I find the node (b and d in this case) by getting the first element in the nodeset, which I find using the following code:

String xPathExpression = "//*[local-name()='b']";
XPathNodeIterator nodeSet = (XPathNodeIterator)navigator.Evaluate(xPathExpression);

and

String xPathExpression = "//*[local-name()='d']";
XPathNodeIterator nodeSet = (XPathNodeIterator)navigator.Evaluate(xPathExpression);

Now using xpath, I just can't figure out which comes first, b or d.


Solution

  • You want to scan the tree in document order (the order the elements occur). As though by chance this is the default search order, and all you've got to do is select the first element which is a <b/> or <d/> node:

    //*[local-name() = 'b' or local-name() = 'd'][1]
    

    If you want the name, add another local-name(...) call:

    local-name(//*[local-name() = 'b' or local-name() = 'd'][1])