Paulb
Paulb

Reputation: 1531

XSLT Remove Tag But Keep Content

I want to remove a tag in XSLT, but leave everything within in place.

I have this source:

<?xml version="1.0" encoding="UTF-8"?>
<DOCUMENT>
    <div>
        <p>foo</p>
        <div>we want any divs found in here</div>
        <p>we want to keep everything</p>
        <p>except the div that follows DOCUMENT</p>
    </div>
</DOCUMENT>

And would like this output:

<?xml version="1.0" encoding="UTF-8"?>
<DOCUMENT>
        <p>foo</p>
        <div>we want any divs found in here</div>
        <p>we want to keep everything</p>
        <p>except the div that follows DOCUMENT</p>
</DOCUMENT>

The unwanted <div> always follows <DOCUMENT> and it's the only <div> I wanted deleted.

I am able to do this with this XSLT

<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="/DOCUMENT/div">
        <xsl:apply-templates select="@*|node()"/>
</xsl:template>

</xsl:stylesheet>

Issue: I don't want to do this with the identity-transform template because I'm working on a "pull" transform, not push. But I'm stumped to find an alternative.

Upvotes: 2

Views: 3750

Answers (1)

Christian Manthey
Christian Manthey

Reputation: 98

Well, when you are working with a pull stylesheets, isn't it the easiest way to simply select all elements under DOCUMENTS/div?

Example:

<xsl:template match="/">
<DOCUMENT>
    <xsl:for-each select="DOCUMENT/div/*">
    <xsl:copy-of select="."/>
    </xsl:for-each>
</DOCUMENT>
</xsl:template>

When trying this I get this result:

<DOCUMENT>
<p>foo</p>
<div>we want any divs found in here</div>
<p>we want to keep everything</p>
<p>except the div that follows DOCUMENT</p>
</DOCUMENT>

Upvotes: 4

Related Questions