tags:

views:

524

answers:

3

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.

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

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.


EDIT :

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.

+3  A: 

Did you tried this?

//@lang[1]

here you can see an example.

Artem Barger
Nope I didn't ! At first sight it seems a lot better, I'll make a thorough test right away ! Thanks.
subtenante
Actually it doesn't work properly, it selects all the first lang elements within their parent element.
subtenante
+1  A: 

The following XPath seems to do what you want:

//*[@lang][1]/attribute::lang
Adam Batkin
Hmm I'm afraid it does the same thing...
subtenante
@subtenante: Knowing nothing else about your input I'd say that this should work (and it explains why your try does not). @Artem Barger's solution is a lot more elegant, though.
Tomalak
@Tomalak : unfortunately it doesn't and I can't explain why either.
subtenante
+2  A: 

After some more tackling, here is a working solution :

 (//@lang)[1]

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).

subtenante