XPath: searching for a node attribute (and only one)

What is XPath to find only ONE node (whatever) that has a specific attribute (in fact, this attribute interests me, not node). For example, in my XML, I have several tags that have the lang attribute. I know that they should all have the same value. I just want to get them.

Right now, I am doing this: //*[1][@lang]/@lang , but it seems that it is not working properly for an unknown reason.

My attempts led me to things, ranging from concatenating all @lang values ​​("en en en en ...") to zero, sometimes in between, what I want, but not for all XML.


EDIT:

Actually //@lang[1] cannot work, because the position() function is called before the tag before calling lang . Therefore, it always accepts the very first element found in XML. It worked best at the time, because many times the lang attribute was on the root element.

+4
source share
3 answers

After some solution to the problem, here is a working solution:

  (//@lang)[1] 

Parentheses are needed to separate [1] by attribute name, otherwise the position() function is used in the attribute's parent element (which is useless since there can only be one attribute of a particular name in a tag: why //@lang[2] always doesn’t select anything) .

+6
source

Have you tried this?

 //@lang[1] 

here you can see an example.

+2
source

The following XPath seems to do what you want:

 //*[@lang][1]/attribute::lang 
+1
source

All Articles