在 XSLT 中使用 fn:sum 和包含空值的节点集 [英] Using fn:sum in XSLT with node-set containing null-values
问题描述
我正在尝试使用 XSLT 和 XPath 函数 fn:sum 在 XML 中总结一组值.只要值不为空,这就可以正常工作,但事实并非如此.为了说明我的问题,我举了一个例子:
I'm trying to sum up a set of values in an XML using XSLT and XPath function fn:sum. This works fine as long as the values are non-null, however this is not the case. 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>
和 XML:
<?xml version="1.0"?>
<root>
<values>
<value>1</value>
<value>2</value>
<value>3</value>
<value>4</value>
<!-- Nullvalue -->
<value />
</values>
</root>
只要没有空值,示例就可以正常工作.我尝试了选择的各种变体,例如 <xsl:value-of select="fn:sum(values[value != '']/value)"/>
(如您可能会注意到,没有多少 XSLT 导出 ;) ) 如何过滤掉空值?
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?
推荐答案
显式测试节点是否有内容:
Explicitly test that the nodes have content:
<sum><xsl:value-of select="fn:sum(values/value[text()])" /></sum>
我认为你提到的:
<xsl:value-of select="fn:sum(values[value != '']/value)" />
不起作用,因为节点是空的 - 它根本不包含文本节点,而 value != ''
测试空字符串 - 即,具有数据的文本节点长度为 0.
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.
这篇关于在 XSLT 中使用 fn:sum 和包含空值的节点集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!