David Saintloth
David Saintloth

Reputation: 4241

selecting specific subelement node trees for output using xslt

I have some XML that has an extra element and I want it gone. Input XML:

<top><middle><bottom><!-- other elements --><stuff/></bottom></middle></top>

Output desired:

<top><bottom><!--other elements --><stuff/></bottom></top>

(note "middle" element has been snipped from the node tree)

How do I arbitrarily snip out an element without having to create a template cascade of every possible element in the source? Is there a way to just pass all elments and subelements from a given point? including the XML tagging, attributes and content?

Searches I've done mention using <xsl:copy> but it doesn't work - "node()|@*" only returns the content and attribute value and not the actual subelement XML tree.

How do I do this in XSLT 1 or 2? The way I am doing it now is to create a template tree for each element but the "stuff"?

Upvotes: 1

Views: 411

Answers (1)

Wayne
Wayne

Reputation: 60414

Use the Identity Transform with an override for the elements you want to remove:

<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="middle">
      <xsl:apply-templates/>
  </xsl:template>
</xsl:stylesheet>

Upvotes: 2

Related Questions