ChatGPT解决这个技术问题 Extra ChatGPT

How to write an XPath query to match two attributes?

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!


B
Brian Agnew
//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.


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, together with a helper function to convert iterators into arrays.
z
zhangyangyu

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


C
CodeMonkey

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


M
Manjesh

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