【问题标题】:XSLT for removing tags from a XML fileXSLT 用于从 XML 文件中删除标签
【发布时间】:2011-09-06 01:32:31
【问题描述】:

我有这个 XML 文件:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<results>
  <output>
    <status>OK</status>
    <usage>Please use it</usage>
    <url/>
    <language>english</language>
    <category>science_technology</category>
    <score>0.838661</score>
  </output>
</results>

我想从此 XML 中删除标签 &lt;output&gt; &lt;/output&gt;

预期输出

<?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>

我该怎么做?

【问题讨论】:

  • 显示您想要的确切输出,否则我们只是在猜测。
  • 好问题,+1。请参阅我的答案,了解基于最基本和最强大的 XSLT 设计模式的完整、简短和简单的解决方案 - 身份规则的覆盖。
  • 可以有多个&lt;output&gt;标签吗?

标签: xml xslt xsd


【解决方案1】:

最简单的方法(几乎是机械地,无需思考):

<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>

当此转换应用于提供的 XML 文档时

<results>
  <output>
    <status>OK</status>
    <usage>Please use it</usage>
    <url/>
    <language>english</language>
    <category>science_technology</category>
    <score>0.838661</score>
  </output>
</results>

产生想要的正确结果

<results>
   <status>OK</status>
   <usage>Please use it</usage>
   <url/>
   <language>english</language>
   <category>science_technology</category>
   <score>0.838661</score>
</results>

解释

  1. 身份规则/模板“按原样”复制每个节点。

  2. 有一个模板覆盖了身份规则。它匹配任何output 元素并防止将其复制到输出,但会继续处理其任何子元素。

记住:重写标识规则是最基本和最强大的 XSLT 设计模式。

【讨论】:

  • 非常感谢您的详细解释。它奏效了。我想了解更多关于 XLST 的信息。有没有我可以参考的链接来理解它,因为我有各种 XML 文件需要从中获取数据..
  • @aniket69:在 SO 表达感谢的既定方式是接受最佳答案——点击旁边的复选标记。我很高兴我的回答很有用。是的,XSLT 漂亮、强大且优雅。有关书籍和教程的链接,请参见此链接:stackoverflow.com/questions/339930/…
【解决方案2】:

尽可能短:

<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>

或使用身份规则:

<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多