开发者

XSLT for removing tags from a XML file

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:

  1. The identity rule/template copies every node "as is".

  2. 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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜