How to write an XPath query to match two attributes?

Xpath

Xpath Problem Overview


Following Question:

<div id="id-74385" class="guest clearfix" style="z-index: 999;">

Given above,

If I want a XPath expression with checks both id and class, can we do it w/ 'and' condition LIKE:

//div[@id='id-74385'] and div[@class='guest clearfix']

Is this correct way? My execution fails here... Please help!

Xpath Solutions


Solution 1 - Xpath

//div[@id='..' and @class='...]

should do the trick. That's selecting the div operators that have both attributes of the required value.

It's worth using one of the online XPath testbeds to try stuff out.

Solution 2 - Xpath

or //div[@id='id-74385'][@class='guest clearfix']

Solution 3 - Xpath

Adding to Brian Agnew's answer.

You can also do //div[@id='..' or @class='...] and you can have parenthesized expressions inside //div[@id='..' and (@class='a' or @class='b')].

Solution 4 - Xpath

Sample XML:

<X>
<Y ATTRIB1=attrib1_value ATTRIB2=attrib2_value/>
</X>

string xPath="/" + X + "/" + Y +
"[@" + ATTRIB1 + "='" + attrib1_value + "']" +
"[@" + ATTRIB2 + "='" + attrib2_value + "']"

XPath Testbed: http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsholaView Question on Stackoverflow
Solution 1 - XpathBrian AgnewView Answer on Stackoverflow
Solution 2 - Xpathuser244278View Answer on Stackoverflow
Solution 3 - XpathCodeMonkeyView Answer on Stackoverflow
Solution 4 - XpathManjeshView Answer on Stackoverflow