164

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!

McDowell
  • 102,869
  • 29
  • 193
  • 261
shola
  • 1,649
  • 2
  • 11
  • 3

4 Answers4

230
//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.

Brian Agnew
  • 254,044
  • 36
  • 316
  • 423
  • Many of the online tools demand XML compliance. For HTML, it's easier to test with the browser's XPath implementation. Here's a [code sample](https://gist.github.com/jpaugh/a07b369e41c7ba03e8a729c8cb8cc122), together with a helper function to convert iterators into arrays. – jpaugh Sep 30 '20 at 16:42
114

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

zhangyangyu
  • 8,052
  • 2
  • 30
  • 42
29

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

CodeMonkey
  • 2,758
  • 21
  • 33
1

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

Manjesh
  • 11
  • 1