25

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?

kjhughes
  • 106,133
  • 27
  • 181
  • 240
Phrixus
  • 1,209
  • 2
  • 19
  • 36

1 Answers1

42

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.

kjhughes
  • 106,133
  • 27
  • 181
  • 240