Tom
Tom

Reputation: 1045

How do I return a different node if the first node doesn't exist in an XPath Query?

I'd like to return a secondary node name if the first doesn't exist, for example:

return xpath_query("/root/(blue|red)");
// return /root/blue, or /root/red if it doesn't exist

Is this possible?

Thanks

Upvotes: 0

Views: 122

Answers (1)

user357812
user357812

Reputation:

Answer: Yes.

That's a valid XPath 2.0 expression:

/root/(blue|red)

Meaning: blue and red children of root root element.

If you want one or the other if that doesn't exist, you could rely on document order like:

/root/(blue|red)[1]

Or to be more explicit like:

/root/(if (blue) then blue else red)

XPath 1.0 translations:

/root/*[self::blue|self::red]

/root/*[self::blue|self::red][1]

/root/*[self::blue|self::red[not(../blue)]]

Upvotes: 3

Related Questions