data_enthusiast
data_enthusiast

Reputation: 185

XPath to exclude certain XML elements?

I have now read many (maybe all) posts on excluding elements in XPath and I just do not get this working. I have no clue why.

Let's say I have the following structure:

<root>
  <elemA>
      Hello World!
  </elemA>
  <elemB>
      This is awesome!
      <elemC>Really!</elemC>
  </elemB>
</root>

No I want all elements except elemC.

Based on what I have read, I tried the following XPath:

Option 1:

//*[not(self::elemC)]

Option 2:

//*[not(name()='elemC')]

Option 3:

//*[name()!='elemC']

I have no clue why this is not working, but suspect some stupid mistake. If I do the exact opposite (i.e. leaving out the not or !) the XPath correctly selects the elemC element.

The result should be this:

<root>
  <elemA>
      Hello World!
  </elemA>
  <elemB>
      This is awesome!
  </elemB>
</root>

Upvotes: 1

Views: 1160

Answers (1)

kjhughes
kjhughes

Reputation: 111726

XPath is for selection. What you want to select does not exist in your XML document.

You need another tool such as XSLT to generate an XML output document based on an input XML document. XSLT can generate your desired output trivially via the identity transformation supplemented with a simple template that suppresses the copying of the element that you do not want (elemC):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="elemC"/>
</xsl:stylesheet>

XPath alone cannot help you.

Upvotes: 2

Related Questions