196

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
  • 107,573
  • 31
  • 204
  • 267
shola
  • 1,969
  • 2
  • 12
  • 3

4 Answers4

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

Ray
  • 7,940
  • 7
  • 58
  • 90
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • 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
127

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

zhangyangyu
  • 8,520
  • 2
  • 33
  • 43
41

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
  • 4,067
  • 1
  • 31
  • 43
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