Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath for elements with attribute not equal or does not exist

Tags:

xml

xpath

I have the following XML format:

<test>
 <table>
   <rows>
     <row ID = "1" Name ="A"/>
     <row ID = "2" SubID = "1" Name ="B"/>
     <row ID = "3" Name ="C"/>
     <row ID = "4" SubID = "1" Name ="D"/>
     <row ID = "5" Name ="E"/>
     <row ID = "4" SubID = "2" Name ="E"/>
   </rows>
   .
   .
 </table>
</test>

I would like to take all the rows except the ones that do have SubID = 1.

The hard part of this, is that not all the rows have attribute called SubID, and that not all the rows with the attribute SubID, have same value.

The ideal output should be:

<row ID = "1" Name ="A"/>
<row ID = "3" Name ="C"/>
<row ID = "5" Name ="E"/>
<row ID = "4" SubID = "2" Name ="E"/>

I have tried to use an XPath with negation on value, but this won't work:

/test/table/row/not(@SubID=1)

Any help?

like image 399
Phrixus Avatar asked Jan 06 '16 12:01

Phrixus


People also ask

What is contain in xpath?

contains() is a Selenium function that searches for web elements that contain a specific text within an Xpath expression. The XPath function contains offers the ability to detect elements containing partial text. They are used in any condition on Xpath. Lets take an HTML code here: <html>


1 Answers

The "hard part" is actually easy: A basic

element[not(@attribute= 'value')]

predicate will exclude elements without the attribute and elements for which attribute equals value.

So, in your specific case, all row elements that do not have @SubID equal to 1:

/test/table/rows/row[not(@SubID = '1')]

selects

<row ID="1" Name="A"/>
<row ID="3" Name="C"/>
<row ID="5" Name="E"/>
<row ID="4" Name="E" SubID="2"/>

as requested.

like image 94
kjhughes Avatar answered Oct 12 '22 14:10

kjhughes