首页 > 解决方案 > 处理 XSLT 输入文件以从 XSLT 中删除特定内容

问题描述

我需要处理 XSLT 代码,如果 XSL 标记元素的属性值为 enable="yes",则必须从输出中删除相应的标记。

我的输入 xsl 文件如下所示,

    <xsl:stylesheet version = "1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="xml" indent="yes" />


    <xsl:template match="/">   
    <xsl:for-each select="Node/Node_1">
    <node>
    <line enable="false"><xsl:value-of select="Line"/></line>
    <text><xsl:value-of select="Text"/></text>
    <desc enable="false"><xsl:value-of select="Desc"/></desc>
    <cust><xsl:value-of select="Cust"/></cust>
    </node>
    </xsl:for-each>
    </xsl:template>    
    </xsl:stylesheet> 

然后输出数据必须删除相应的具有属性 enable="false" 的 XSL 标记,

    <xsl:stylesheet version = "1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="xml" indent="yes" />


    <xsl:template match="/">   
    <xsl:for-each select="Node/Node_1">
    <node>
    <text><xsl:value-of select="Text"/></text>
    <cust><xsl:value-of select="Cust"/></cust>
    </node>
    </xsl:for-each>
    </xsl:template>    
    </xsl:stylesheet> 

通过 XSLT 本身是否可行,将 xsl 文件视为 XML 并对其进行处理以删除具有 enable="false" 属性的标签。或者有没有更好的方法来完成它?

标签: xmlxslt

解决方案


很容易做到这一点,一个空模板<xsl:template match="*[@enable = 'false']"/>和身份转换一起实现了这一点:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="3.0">

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:template match="*[@enable = 'false']"/>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/jyH9rMh是一个 XSLT 3 示例,在早期版本的 XSLT 中,您需要将 替换为<xsl:mode on-no-match="shallow-copy"/>拼写出的身份模板:

<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>

推荐阅读