How to remove XML elements dynamically
I am basically looking for an XSLT (say a callable template), which will take as input an xml AND an element to be deleted in the XML and give me back the final XML after deleting that particular element in the XML.
Exam开发者_JAVA百科ple:
<Request>
<Activity1>XYZ</Activity1>
<Activity2>ABC</Activity2>
</Request>
Now i need an xslt for which i must give the above xml as input and the element to be deleted (Say <Activity1>
) as input. The XSLT must return the final xml after deleting the element passed to it.
You can use a modified copy-template:
<xsl:stylesheet ...>
<xsl:output method="xml" encoding="UTF-8" indent="yes"/>
<xsl:variable name="removeNode">Activity1</xsl:variable>
<xsl:template match="node()">
<xsl:if test="not(name()=$removeNode)">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:if>
</xsl:template>
<xsl:template match="@*">
<xsl:copy>
<xsl:apply-templates select="@*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
How to pass the parameter to yout template depends on your used XSLT-processor.
Edit
Another possibility is to ignore the node when needed:
<xsl:template match="/">
<xsl:apply-templates select="*/*[not(self::element-to-ignore)]"
mode="renderResult"/>
</xsl:template>
<xsl:template match="@*|node()" mode="renderResult">
<xsl:copy>
<xsl:apply-templates select="@*|node()" mode="renderResult"/>
</xsl:copy>
</xsl:template>
This is a generic transformation that accepts a global (externally specified) parameter with the name of the element to be deleted:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pDeleteName" select="'c'"/>
<xsl:template match="node()|@*" name="identity">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:if test="not(name() = $pDeleteName)">
<xsl:call-template name="identity"/>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
when applied on any XML document (for example the following):
<a>
<b>
<c/>
<d>
<e>
<c>
<f/>
</c>
<g/>
</e>
</d>
</b>
</a>
the correct result is produced -- the source XML document in which any element having name the same as the string in the pDeleteName
parameter -- is deleted:
<a>
<b>
<d>
<e>
<g/>
</e>
</d>
</b>
</a>
As can be clearly seen, any occurence of the element <c>
has been deleted.
精彩评论