tags:

views:

968

answers:

2

I have the problem to get the node if there is more than one attribute.

Example:

<div class="atag btag" />

This is my xpath expression: //*[@class='atag']

The expression only works with <div class="atag" /> but not for the above shown.

Any suggestions?

+1  A: 

EDIT: see bobince's solution which uses contains rather than start-with, along with a trick to ensure the comparison is done at the level of a complete token (lest the 'atag' pattern be found as part of another 'tag').

"atag btag" is an odd value for the class attribute, but never the less, try:

//*[starts-with(@class,"atag")]
mjv
you can use this if your XPath engine supports the starts-with command, for example JVM 6 doesn't support it as far as i remember
Mohamed Faramawi
Thank you - that works fine!
crazyrails
@mjv: It's common for a CSS class attribute to specify multiple values. That's how CSS is done.
skaffman
@mjv You cannot guarantee that that name will appear at the start of the class attribute.
Alan Krueger
@thuktun @skaffman. Thanks, great comments. I 'redirected' to bobince solution accordingly.
mjv
+12  A: 

mjv's answer is a good start but will fail if atag is not the first classname listed.

The usual approach is the rather unwieldy:

//*[contains(concat(' ', @class, ' '), ' atag ')]

this works as long as classes are separated by spaces only, and not other forms of whitespace. This is almost always the case. If it might not be, you have to make it more unwieldy still:

//*[contains(concat(' ', normalize-space(@class), ' '), ' atag ')]

(Selecting by classname-like space-separated strings is such a common case it's surprising there isn't a specific XPath function for it, like CSS3's '[class~="atag"]'.)

bobince
Thanks a lot! I've tested your solution and it works well.
crazyrails
+1 from me, straightforward solution.
Tomalak
bah, xpath needs some fixes
the0ther