简体   繁体   English

在XSLT中使用fn:sum,其中包含包含空值的节点集

[英]Using fn:sum in XSLT with node-set containing null-values

I'm trying to sum up a set of values in an XML using XSLT and XPath function fn:sum. 我试图使用XSLT和XPath函数fn:sum在XML中总结一组值。 This works fine as long as the values are non-null, however this is not the case. 只要值为非null,这样就可以正常工作,但事实并非如此。 To illustrate my problem I've made an example: 为了说明我的问题,我做了一个例子:

<?xml version="1.0"?>

<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:fn="http://www.w3.org/2005/xpath-functions">

  <xsl:template match="/root">
    <root>
      <!-- Works fine for non-null values -->
      <sum><xsl:value-of select="fn:sum(values/value)" /></sum>
    </root>
  </xsl:template>
</xsl:stylesheet>

and the XML: 和XML:

<?xml version="1.0"?>
<root>
  <values>
    <value>1</value>
    <value>2</value>
    <value>3</value>
    <value>4</value>
    <!-- Nullvalue -->
    <value />
  </values>
</root>

The example works fine as long as there's no null-values. 只要没有空值,该示例就可以正常工作。 I've tried various variants of the select, such as <xsl:value-of select="fn:sum(values[value != '']/value)" /> (as you might notice, not much of an XSLT export ;) ) How can I filter out the null-values? 我尝试过各种各样的select变体,比如<xsl:value-of select="fn:sum(values[value != '']/value)" /> (你可能会注意到,XSLT并不多) export;))如何过滤掉空值?

Explicitly test that the nodes have content: 明确测试节点是否有内容:

<sum><xsl:value-of select="fn:sum(values/value[text()])" /></sum>

I think that what you mentioned: 我想你提到的是:

<xsl:value-of select="fn:sum(values[value != '']/value)" /> 

does not work, because the node is empty - it does not contain a text node at all, whereas value != '' tests for an empty string - that is, a text node having data of length 0. 不起作用,因为节点是空的 - 它根本不包含文本节点,而value != ''测试空字符串 - 即具有长度为0的数据的文本节点。

To sum just the elements that contain numbers: 仅总结包含数字的元素:

<sum>
    <xsl:value-of select="fn:sum(values/value[number(.)=number(.)])" />
</sum>

The result of number() will be NaN for empty elements, or elements whose string value is not a number. 对于空元素,或者字符串值不是数字的元素, number()的结果将是NaN

MSDN reference - http://msdn.microsoft.com/en-us/library/ms256211.aspx MSDN参考 - http://msdn.microsoft.com/en-us/library/ms256211.aspx

http://www.stylusstudio.com/xsllist/199909/post60110.html http://www.stylusstudio.com/xsllist/199909/post60110.html

XML: XML:

<?xml version="1.0"?>
<doc>
    <num>1</num>
    <num>7</num>
    <notnum>hello world</notnum>
    <num>4</num>
</doc>

XSLT: XSLT:

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/XSL/Transform/1.0">
    <xsl:template match="/">
        <xsl:value-of select="sum(/doc/num)"/>
    </xsl:template>
</xsl:stylesheet>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM