Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath selection while excluding elements having certain attribute values

My first post here - it's a great site and I will certainly do my best to give back as much as I can.

I have seen different manifestations of this following question; however my attempts to resolve don't appear to work.

Consider this simple tree:

<root>
    <div>
        <p>hello</p>
        <p>hello2</p>
        <p><span class="bad">hello3</span></p>
    </div>
</root>

I would like to come up with an XPath expression that will select all child nodes of "div", except for elements that have their "class" attribute equal to "bad".

Here is what I have tried:

/root/div/node()[not (@class='bad')]

... However this doesn't seem to work.

What am I missing here?

Cheers,
Isaac

like image 358
Isaac Avatar asked Sep 09 '10 20:09

Isaac


People also ask

What does * indicate in XPath?

The XPath default axis is child , so your predicate [*/android.widget.TextView[@androidXtext='Microwaves']] is equivalent to [child::*/child::android.widget.TextView[@androidXtext='Microwaves']] This predicate will select nodes with a android. widget. TextView grandchild and the specified attribute.

What is text () function in XPath?

The XPath text() function is a built-in function of selenium webdriver which is used to locate elements based on text of a web element. It helps to find the exact text elements and it locates the elements within the set of text nodes. The elements to be located should be in string form.


2 Answers

I have been working with XPath in a Java program I'm writing. If you want to select the nodes that don't have class="bad" (i.e. the <span> nodes, but not the surrounding <p> nodes), you could use:

/root/div/descendant::*[not (@class='bad')]

Otherwise, if you want to select the

nodes that don't have a child with class='bad', you can use something like the following:

/root/div/p/*[not (@class='bad')]/..

the .. part selects the immediate parent node.

like image 33
hemelamed Avatar answered Oct 08 '22 07:10

hemelamed


When testing your XPath here with the provided XML document, the XPath seems to be indeed selecting all child nodes that do not have an attribute class="bad" - these are all the <p> elements in the document.

You will note that the only child node that has such an attribute is the <span>, which indeed does not get selected.

Are you expecting the p node surrounding your span not to be selected?

like image 130
Oded Avatar answered Oct 08 '22 09:10

Oded