user2092096
user2092096

Reputation: 173

XSLT Copy all Nodes except 1 element

<events>
    <main>
        <action>modification</action>
        <subAction>weights</subAction>
    </main>
</events>
<SeriesSet>
    <Series id="Price_0">
        <seriesBodies>
            <SeriesBody>
                <DataSeriesBodyType>Do Not Copy</DataSeriesBodyType>
            </SeriesBody>
        </SeriesBodies>
    </Series>
</SeriesSet>

How do i copy all xml and exclude the DataSeriesBodyType element

Upvotes: 13

Views: 37076

Answers (2)

Guasque&#241;o
Guasque&#241;o

Reputation: 447

The following works for me as sometimes I need to create a tree without one element to make a variable and some times remove another to make another variable. Note that the main match should not match the root element "/" because if you do, it copies the whole three down only when processing just the one root element. But keep in-mind this solutions where we use apply-templates for all nodes will interfere with other templates you may have to do other jobs, so you would need to us the "mode" option to separate them.

    <xsl:template match="node()|@*">
       <xsl:copy>
         <xsl:apply-templates select="node()[not(self::DataSeriesBodyType)]|@*"/>
       </xsl:copy>
    </xsl:template>

Upvotes: 1

Pablo Pozo
Pablo Pozo

Reputation: 1920

You just have to use the identity template (as you were using) and then use a template matching DataSeriesBodyType which does nothing.

The code would be:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">


    <xsl:output method="xml" encoding="utf-8" indent="yes"/>

    <!-- Identity template : copy all text nodes, elements and attributes -->   
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <!-- When matching DataSeriesBodyType: do nothing -->
    <xsl:template match="DataSeriesBodyType" />

</xsl:stylesheet>

If you want to normalize the output to remove empty data text nodes, then add to the previous stylesheet the following template:

<xsl:template match="text()">
    <xsl:value-of select="normalize-space()" />
</xsl:template>

Upvotes: 28

Related Questions