Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSL: how to copy a tree, but removing some nodes?

Tags:

xslt

I want to use XSL to remove some elements from a tree.

Suppose I have the following XML tree:

<?xml version="1.0" ?>
<mydoc>
    <file>
        <colors>
            <blue />
            <red />
            <green />
        </colors>
        <secret>
            <username />
            <password />
        </secret>
    </file>
</mydoc>

I want to remove the username and password nodes from it. How would I proceed with XSL ?

like image 866
Leonel Avatar asked Jul 16 '09 13:07

Leonel


People also ask

How do I copy a node in XSLT?

XSLT <xsl:copy-of> The <xsl:copy-of> element creates a copy of the current node. Note: Namespace nodes, child nodes, and attributes of the current node are automatically copied as well! Tip: This element can be used to insert multiple copies of the same node into different places in the output.

What does xsl copy do?

Causes the current XML node in the source document to be copied to the output. The actual effect depends on whether the node is an element, an attribute, or a text node.

How many trees are involved in xsl transformation?

Unlike CSS, XSL is not limited to working only with whole elements. It has a much more granular view of a document that enables you to base styles on comments, attributes, processing instructions, element content, and more. XSLT operates by transforming one XML tree into another XML tree.


1 Answers

You want an identity transform. A common design pattern in XSLT is a transform that will copy everything. Then you add templates to remove or transform what is different between the source and the target.

<?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="username|password"/> <!-- this empty template will remove them -->
</xsl:stylesheet>
like image 57
lavinio Avatar answered Sep 30 '22 11:09

lavinio