I have this XML file:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<results>
<output>
<status>OK</status>
&开发者_运维百科lt;usage>Please use it</usage>
<url/>
<language>english</language>
<category>science_technology</category>
<score>0.838661</score>
</output>
</results>
I want to remove the tags <output> </output>
from this XML.
OUTPUT EXPECTED
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<results>
<status>OK</status>
<usage>Please use it</usage>
<url/>
<language>english</language>
<category>science_technology</category>
<score>0.838661</score>
</results>
How can I do this?
The easiest way to do this (almost mechanically and without thinking):
<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:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="output"><xsl:apply-templates/></xsl:template>
</xsl:stylesheet>
when this transformation is applied on the provided XML document:
<results>
<output>
<status>OK</status>
<usage>Please use it</usage>
<url/>
<language>english</language>
<category>science_technology</category>
<score>0.838661</score>
</output>
</results>
the wanted, correct result is produced:
<results>
<status>OK</status>
<usage>Please use it</usage>
<url/>
<language>english</language>
<category>science_technology</category>
<score>0.838661</score>
</results>
Explanation:
The identity rule/template copies every node "as is".
There is a single template overriding the identity rule. It matches any
output
element and prevents it from being copied to the output, but continues the processing of any of its children.
Remember: Overriding the identity rule is the most fundamental and most powerful XSLT design pattern.
Shortest as possible:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="results">
<xsl:copy>
<xsl:copy-of select="output/*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
or using identity rule:
<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="results">
<xsl:copy>
<xsl:apply-templates select="output/*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
精彩评论