XSLT add not existing nodes

為{幸葍}努か 提交于 2019-12-25 07:48:16

问题


I have an XML fragment like this

<lines>
    <item><code>1.1</code><amt>1000.00</amt></item>
    <item><code>1.3.1</code><amt>2000.00</amt></item>
    <item><code>1.3.2</code><amt>3000.00</amt></item>
    <item><code>2.1</code><amt>4000.00</amt></item>
    ...
</lines>

I want to make a sum of all 1* nodes. The full list is known so I can write something like:

<xsl:value-of select="item[code=1.1]/amt + 
 item[code=1.2]/amt + item[code=1.3.1]/amt + item[code=1.3.2]/amt"/>

The issue is that any (even all) of those nodes can be absent (like 1.2 in the example). So the statement returns NaN !

Would appreciate some good advise :)

Alex


回答1:


In this case since it's a straight sum you could just do

<xsl:value-of select="sum(item[code=1.1 or code=1.2 or
                               code=1.3.1 or code=1.3.2]/amt)"/>



回答2:


You can use this provided all the amt are valid decimals:

 <xsl:value-of select="sum(item[starts-with(code, '1')]/amt)"/>

And if you want to sum only the numbers and omit NaN values(in case any), use this:

<xsl:value-of select="sum(item[starts-with(code, '1.') and number(amt)]/amt)"/>


来源:https://stackoverflow.com/questions/28717526/xslt-add-not-existing-nodes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!