XPath - 选择与值相等的元素 [英] XPath - Selecting elements that equal a value

查看:40
本文介绍了XPath - 选择与值相等的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Xpath 中,我想选择等于特定值的元素.

In Xpath, I am wanting to select elements that equal a specific value.

示例 XML 数据:

<aaa id="11" >
    <aaa id="21" >
        <aaa id="31" ></aaa>
        <bbb id="32" >
            <aaa id="41" ></aaa>
            <bbb id="42" ></bbb>
            <ccc id="43" ></ccc>
            <ddd id="44" >qwerty</ddd>
            <ddd id="45" ></ddd>
            <ddd id="46" ></ddd>
        </bbb>
    </aaa>
    <bbb id="22" >
         <aaa id="33" >qwerty</aaa>
         <bbb id="34" ></bbb>
         <ccc id="35" ></ccc>
         <ddd id="36" ></ddd>
         <ddd id="37" ></ddd>
         <ddd id="38" ></ddd>
    </bbb>
    <ccc id="23" >qwerty</ccc>
    <ccc id="24" ></ccc>
 </aaa>

现在,使用 XPath:

Now, using the XPath:

//ccc[.='qwerty']

我得到了正确的预期结果:

Name    Value
ccc     qwerty

现在,使用 XPath:

Now, using the XPath:

//aaa[.='qwerty']

我得到了意想不到的结果:

Name    Value
aaa      
aaa     qwerty

我特别感兴趣的是如何选择任何具有该值的元素

And what I am particularly interested, is how to select any element with that value

XPath:

//*[.='qwerty']

我得到了非常奇怪的意外结果:

I get very strange unexpected results:

Name    Value
aaa
bbb
ddd     qwerty
bbb     qwerty
aaa     qwerty
ccc     qwerty

谁能解释这些结果,以及如何修复我的 XPath 表达式以获得更多预期结果?

Can someone explain these results, and how to fix my XPath expressions to get more expected results?

推荐答案

XPath 规范.将元素的字符串值定义为其所有文本节点后代的串联(按文档顺序).

The XPath spec. defines the string value of an element as the concatenation (in document order) of all of its text-node descendents.

这解释了奇怪的结果".

This explains the "strange results".

可以使用以下表达式获得更好"的结果:

"Better" results can be obtained using the expressions below:

//*[text() = 'qwerty']

以上选择了文档中至少有一个值为qwerty"的文本节点子节点的每个元素.

The above selects every element in the document that has at least one text-node child with value 'qwerty'.

//*[text() = 'qwerty' and not(text()[2])]

上面选择了文档中只有一个文本节点子节点的每个元素,其值为:'qwerty'.

The above selects every element in the document that has only one text-node child and its value is: 'qwerty'.

这篇关于XPath - 选择与值相等的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆