Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude specific tag from selection in XPath

Tags:

xml

xpath

I know this is a simple question, but I can't figure it out. Consider the following simple XML document:

<root>
  <a></a>
  <b></b>
  <c></c>
  <a></a>
  <d></d>
  <e></e>
  <a></a>
  <a></a>
</root>

What's the best way to select the nodes <b> through <e> using XPath?

I'm looking for something like

/root/*[not(a)]

(which does not do the trick)

like image 601
user123444555621 Avatar asked Jul 01 '09 11:07

user123444555621


People also ask

How do you find the XPath of an nth element?

By adding square brackets with index. By using position () method in xpath.

What is XPath parsing?

It defines a language to find information in an XML file. It is used to traverse elements and attributes of an XML document.


3 Answers

/root/*[not(self::a)] 
like image 166
Tomalak Avatar answered Sep 23 '22 06:09

Tomalak


Answering to add that in XPath 2.0, you can use except:

/root/(* except a) 

For XPath 1.0, Tomalak pointed out, this is the standard way to do it:

/root/*[not(self::a)] 

By the way, if someone lands here trying to use this in XSLT 2.0 in a xsl:template/@match attribute it won't work because @match takes patterns which although look like XPath expressions, are not XPath expressions. The solution for XPath 1.0 would work in this case.

like image 36
Louis Avatar answered Sep 21 '22 06:09

Louis


I realize this is an old question, but I recently ran into a similar problem and used the following xpath to solve it:

/root/*[not(name()='a')]
like image 23
BVH Avatar answered Sep 20 '22 06:09

BVH