XSLT Copy all Nodes except 1 element

2019-04-06 17:29发布

问题:

<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

回答1:

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>


标签: xml xslt