Home > Software design >  How to select all except first element matching criteria using XPath?
How to select all except first element matching criteria using XPath?

Time:08-03

I have XML like this below. I want to create XPath that will select all nodes except the first "default" node. So in this case, I need to select all but the node with the value "2".

<root>
<a default="False">1</a>
<a default="True">2</a>
<a default="False">3</a>
<a default="False">4</a>
<a default="True">5</a>
<a default="False">6</a>
<a default="False">7</a>
</root>

CodePudding user response:

If you want to select all nodes except first one try

//a[position() > 1]

If you want to select all nodes except the first one that has @default="True" try

//a[@default="True"][position() != 1]|//a[@default="False"]

CodePudding user response:

In XPath 2.0 , you can use

//a except //a[@default='true'][1]

(You really should say which XPath version you are asking about).

It's tricky in XPath 1.0, but you can use the complicated formula that A except B can be written A[not(. | B)], so it becomes //a[not(. | //a[@default='true'][1])]. Or you could exploit the fact that the nodes all have distinct content, and write //a[not(. = //a[@default='true'][1])].

  • Related