使用XPath是否可以将目标节点的路径中的每个节点的名称作为String?

时间:2014-11-12 21:23:50

标签: xml xpath xpath-2.0

使用XPath是否可以将目标节点路径中每个节点的名称作为字符串获取?

的example.xml

<parent>
    <childOne>
        <target>true</target>
    </childOne>

    <childTwo>
        <target>true</target>
    </childTwo>

    <childThree>
        <target>false</target>
    </childThree>
</parent>

选择目标为真的所有祖先

//node()[target = "true"]/ancestor-or-self::*

是否可以获得此结果

"parent/childOne/target"

"parent/childTwo/target"

1 个答案:

答案 0 :(得分:2)

这个XPath 2.0表达式怎么样:

string-join(for $node in //node()[text() = 'true'] return string-join(for $ancestor in $node/ancestor-or-self::* return concat('/',local-name($ancestor)), ''), '&#10;')

这将返回由换行符分隔的路径字符串。如果您想要使用每个路径的单独结果节点

for $node in //node()[text() = 'true'] return string-join(for $ancestor in $node/ancestor-or-self::* return concat('/',local-name($ancestor)), '')

代替。

请注意,我必须将target = 'true'更改为text() = 'true',以便将代码包含在最低级别。

部分路径字符串串联的技巧受到了这个答案的启发:Concatenate multiple node values in xpath

相关问题