Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath 1.0 to find if an element's value is in a list of values

Is there a way to construct an XPath that evaluates whether an element's value is in a predefined list of values? Something akin to this:

/Location/Addr[State='TX or AL or MA'] 

Which would match nodes whith State elements for Texas, Alabama, or Massachusetts? I know that I can unpack the expression:

/Location/Addr[State='TX] or  /Location/Addr[State='AL'], etc... 

But this is a bit cumbersome since the xpaths are quite long, as is the list of values. My google-fu isn't turning up much on the issue...

like image 953
user364902 Avatar asked Jun 11 '10 20:06

user364902


People also ask

What is the * indicates in XPath?

Then you'd select all element nodes with an @id -attribute-value equal to 'Passwd' in the whole document. Just add //* in the XPath -- it highlights --- various page elements. This would select all element nodes in the whole document.

How write multiple contains in XPath?

$xml->xpath("(//person)[firstname[contains(., 'Kerr')]]"); then it works fine.

How do you write conditional XPath expression?

To define an XPath expression that checks if a string element is empty, you must use the operator != . This example shows how to define an XPath expression that evaluates to true when a repeating element, which is referred to as a sequence, is empty. The effective Boolean value of an empty sequence is false.

What is XPath expression to select all the book elements?

/bookstore/book[price>35.00] Selects all the book elements of the bookstore element that have a price element with a value greater than 35.00. /bookstore/book[price>35.00]/title. Selects all the title elements of the book elements of the bookstore element that have a price element with a value greater than 35.00.


1 Answers

You can check multiple conditions inside the same square brackets:

/Location/Addr[State='TX' or State='AL' or State='MA'] 

Or if you have a really long list, you can create a list of states and use the contains() function.

/Location/Addr[contains('TX AL MA', State)] 

This will work fine for two-letter state abbreviations. If you want to make it more robust for longer strings you could add some spaces on the ends and check for _TX_, _AL_, etc. (where the underscores are spaces).

/Location/Addr[contains(' TX AL MA ', concat(' ', State, ' '))] 
like image 65
John Kugelman Avatar answered Oct 02 '22 12:10

John Kugelman