XPath :查找属性节点(并且只有一个) [英] XPath : finding an attribute node (and only one)

查看:31
本文介绍了XPath :查找属性节点(并且只有一个)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅查找具有特定属性的一个节点(以哪个为准)的 XPath 是什么(实际上我对属性感兴趣,而不是节点).例如,在我的 XML 中,我有几个具有 lang 属性的标签.我知道它们都必须具有相同的值.我只想得到其中任何一个.

What is the XPath to find only ONE node (whichever) having a certain attribute (actually I'm interested in the attribute, not the node). For example, in my XML, I have several tags having a lang attribute. I know all of them must have the same value. I just want to get any of them.

现在,我这样做://*[1][@lang]/@lang,但它似乎无法正常工作,原因不明.

Right now, I do this : //*[1][@lang]/@lang, but it seems not to work properly, for an unknown reason.

我的尝试使我想到了从所有@lang 值('en en en en ...')的串联到无,有时介于我想要的但不是所有 XML 之间的事情.

My tries have led me to things ranging from concatenation of all the @lang values ('en en en en...') to nothing, with sometimes inbetween what I want but not on all XML.

其实//@lang[1]是不行的,因为position()函数是在对一个lang进行测试之前调用的属性存在.所以它总是采用在 XML 中找到的第一个元素.当时效果最好,因为很多时候,lang 属性都在根元素上.

Actually //@lang[1] can not work, because the function position() is called before the test on a lang attribute presence. So it always takes the very first element found in the XML. It worked best at the time because many many times, the lang attribute was on root element.

推荐答案

经过更多的处理,这里有一个可行的解决方案:

After some more tackling, here is a working solution :

 (//@lang)[1]

需要括号将[1]与属性名称分开,否则position()函数会应用在属性的父元素内(这是无用的因为在一个标签中只能有一个特定名称的属性:这就是为什么 //@lang[2] 总是不选择任何东西的原因).

Parentheses are needed to separate the [1] from the attribute name, otherwise the position() function is applied within the parent element of the attribute (which is useless since there can be only one attribute of a certain name within a tag : that's why //@lang[2] always selects nothing).

这篇关于XPath :查找属性节点(并且只有一个)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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