【问题标题】:XSL Ignoring Elements that are Blank or Equal to 0XSL 忽略空白或等于 0 的元素
【发布时间】:2014-11-20 07:55:55
【问题描述】:

我正在执行 XSLT 转换,我想忽略值为零的元素以及空白元素。我正在使用的 XML 示例如下所示

<row>
 <col1>a</col1>
 <col2></col2>
 <col3>0</col3>
</row>

例如,我尝试过使用:

<xsl:if test="col2 != '0' or col2 != ' '><xsl:value-of select="col2"/></xsl:if>

但它会过滤掉所有内容,而不仅仅是过滤空白或零的数据。但这不起作用。我做错了什么?

【问题讨论】:

  • 为了将来参考,而不是说“这不起作用”,您需要准确解释正在发生的事情。您收到错误消息吗?是什么都没有输出,还是您不期望的其他东西?显示您的实际输出和预期输出将有很大帮助。谢谢!

标签: xml xslt


【解决方案1】:

您做错了什么是您使用的是or 而不是and。此外,您还要检查单个空格,而不是空元素。因此,如果您将空格视为“空白”,则应使用 normalize-space 函数

<xsl:if test="col2 != '0' and normalize-space(col2) != ''">

注意,根据您实际想要实现的目标,在这里使用模板匹配可能会更好,而不是xsl:if

试试这个例子

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

    <xsl:template match="row">
        <xsl:copy>
            <xsl:apply-templates select="*[. != '0' and normalize-space(.) != '']" />
        </xsl:copy>
    </xsl:template>

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

或者,您可以使用“拉”方法,并编写模板以忽略空元素(而不是专门选择要复制的元素)。这也行

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

    <xsl:template match="row/*[. = '0' or normalize-space(.) = '']" />

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

【讨论】:

    【解决方案2】:

    您的测试是经典的重言式:x!=a 或 x!=b 始终为真,因为当 x=a 时第二个命题为真,当 x=b 时第一个命题为真,而当 x= c,两者都是真的。在逻辑上,你需要写 x!=a AND x!=b。

    就 XSLT 而言,如果 col2 应该是一个非零数值,您可以将您的测试表述为:

    <xsl:if test="number(col2)">
    

    我不确定您在什么情况下测试它;通常最好在处理它们之前消除不需要的元素,例如:

    <xsl:apply-templates select="col2[boolean(number(.))]"/> 
    

    【讨论】:

      【解决方案3】:

      你也可以试试这个

        <xsl:for-each select="row/*">
          <xsl:if test="normalize-space(.)!=''">
            <xsl:if test=".!='0'">
              <xsl:copy-of select="."/>
            </xsl:if>
          </xsl:if>               
        </xsl:for-each>
      

      【讨论】:

        猜你喜欢
        • 2018-03-31
        • 2018-07-05
        • 1970-01-01
        • 1970-01-01
        • 2021-12-11
        • 2021-02-17
        • 1970-01-01
        • 1970-01-01
        • 2018-11-20
        相关资源
        最近更新 更多