xpath get first element based on condition

Viewed 371

I need my xpath expression to select only the first child element of an xml file based on condition. Say the first having field1=B. I use this expression but it return that with field1=A.

<root>
<entry>
    <field1>A</field1>
    <field2>10</field2>
</entry>
<entry>
    <field1>B</field1>
    <field2>20</field2>
</entry>
/root/entry[//field1='B' or 'C'][1]

How can I do it?

1 Answers

It should be

/root/entry[.//field1='B' or .//field1='C'][1]

Note that entry[//field1='B'][1] means return first entry node if field1 node with value 'B' exists (anywhere in XML) while entry[.//field1='B'][1] means return first entry node if it has a descendant field1 node with value 'B'

Also you can simplify expression as

/root/entry[field1='B' or field1='C'][1]

if field1 always appears as direct child of entry

Related