Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use XPath to select multiple possible text values?

Tags:

xml

xpath

I have to select rating codes out of a ratings tag similar to the one below, but only when the agency is 'SP' or 'SNP'. Right now I have:

./ratings/rating/agency[text()='SNP'|text()='SP']/../code

This doesn't seem to be working though. What am I doing wrong?

<ratings>
  <rating>
    <agency>SP</agency>
    <provider>SP</provider>
    <type>LONG TERM</type>
    <currencyType>LOCAL</currencyType>
    <description>SP Standard LT LC rating</description>
    <code>BBB+</code>
    <date>2011-09-07</date>
  </rating>
</ratings>

Thanks,

Jared

like image 382
Jared Avatar asked Oct 28 '11 19:10

Jared


People also ask

How do you locate multiple elements with the same XPath?

If an xpath refers multiple elements on the DOM, It should be surrounded by brackets first () and then use numbering. if the xpath refers 4 elements in DOM and you need 3rd element then working xpath is (common xpath)[3].

How can find XPath using two attributes?

At the time of working XPath multiple attributes, we can use two or more attributes in a single class. We can utilize the distinct attribute available for only the tag or attribute combination and values for identifying the element, for the same we need to use the XPath multiple expression.


2 Answers

The main thing is the union operator | which you've tried to use as an 'or'. Change it to or:

./ratings/rating/agency[text()='SNP' or text()='SP']/../code

Or more naturally,

ratings/rating[agency[. = 'SNP' or . = 'SP']]/code

In XPath 2.0, you can use a sequence:

ratings/rating[agency = ('SNP', 'SP')]/code
like image 181
LarsH Avatar answered Oct 29 '22 23:10

LarsH


Use or instead of |

./ratings/rating/agency[text()='SNP' or text()='SP']/../code
like image 45
Kirill Polishchuk Avatar answered Oct 29 '22 23:10

Kirill Polishchuk