Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Xpath - select where element = multiple values

Fairly straightforward question, but seems pretty hard to find what I want through search, here or Google.

Most people ask how you can select a node/ element with multiple conditions.

Like URL/books[title="Harry Potter" and author="JKRowling"]

I want to know if there's a way to shorten that syntax if you have multiple possibilities for one attribute.

In other words

URL/books[price=1 or price=2 or price=3 or price=8 or price=15]

Is there a way to shorten that syntax?

Like URL/books[price=1,2,3] or [price in (1,2,3)] ---- obviously these are wrong, but would make things easier.

like image 459
John Babson Avatar asked Oct 25 '25 03:10

John Babson


1 Answers

XPath 2.0 would allow

URL/books[price=(1,2,3)]

The = operator (and also !=, <, >, <= and >=) in XPath has an implicit existential quantifier when either or both of its operands are sequences - X = Y is true if any member of the sequence X is equal to any member of the sequence Y. Note that this means that X != Y is not necessarily the same as not(X = Y) - the former means there is some pair of X and Y values that are not equal (and there might also be other pairs that are equal), the latter means that there are no equal pairs at all.

However XPath 1.0 doesn't support sequences of atomic values like this, its only multi-valued data type is the node set. If you could somehow inject a variable with the list of values as XML, e.g.

<prices>
  <price>1</price>
  <price>2</price>
  <price>3</price>
</prices>

then you could say

URL/books[price = $var/prices/price]

but that (a) depends on whether and how your XPath engine supports variable bindings and (b) is probably less clear than just enumerating price = 1 or price = 2 ... anyway.

like image 161
Ian Roberts Avatar answered Oct 28 '25 03:10

Ian Roberts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!