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_q开发者_运维问答uery("/root/(blue|red)");
// return /root/blue, or /root/red if it doesn't exist
Is this possible?
Thanks
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)]]
精彩评论