如果 XPath 查询中不存在第一个节点,我如何返回不同的节点?
问题描述:
如果第一个不存在,我想返回一个辅助节点名称,例如:
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
这可能吗?
谢谢
答
答案:是的.
这是一个有效的 XPath 2.0 表达式:
That's a valid XPath 2.0 expression:
/root/(blue|red)
含义: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]
或者更明确地说:
/root/(if (blue) then blue else red)
XPath 1.0 翻译:
XPath 1.0 translations:
/root/*[self::blue|self::red]
/root/*[self::blue|self::red][1]
/root/*[self::blue|self::red[not(../blue)]]