有什么方法可以使用XSLT从String中获取数字并计算相同的总和?

时间:2019-05-13 10:54:09

标签: xml xslt

字符串,例如-

         10 AL @ 6' X 32' ROOFTOP
          5 AL @ 6' X 32' ROOFTOP
          4 AL @ 6' X 32' ROOFTOP
          6 AL @ 6' X 32' ROOFTOP

我需要提取AL之前的所有数字并计算出总和。

我尝试了,但是我得到了NaN作为输出。

来自评论

<part_d>
    <description label="Description Part">1 RL @ 4' X 32'</description>
    <description label="Description Part">10 RL @ 4' X 32'</description> 
    <description label="Description Part">5 RL @ 4' X 32'</description> 
    <description label="Description Part">8 RL @ 4' X 32'</description> 
    <description label="Description Part">9 RL @ 4' X 32'</description> 
</part_d>

1 个答案:

答案 0 :(得分:2)

XSLT 1.0中的sum()函数只能对数字求和,不能对计算求和。尝试这种方式:

XSLT 1.0(+ EXSLT)

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
extension-element-prefixes="exsl">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>

<xsl:template match="part_d">
    <xsl:variable name="quantities">
        <xsl:for-each select="description">
            <q>
                <xsl:value-of select="substring-before(., ' ')" />
            </q>
        </xsl:for-each>
    </xsl:variable>
    <total-quantity>
        <xsl:value-of select="sum(exsl:node-set($quantities)/q)" />     
    </total-quantity>
</xsl:template>

</xsl:stylesheet>

或者,如果您愿意:

XSLT

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

<xsl:template match="part_d">
    <total-quantity>
        <xsl:call-template name="add">
            <xsl:with-param name="items" select="description"/>
        </xsl:call-template>
    </total-quantity>
</xsl:template>

<xsl:template name="add">
    <xsl:param name="items" select="/.."/>
    <xsl:param name="sum" select="0"/>
    <xsl:choose>
        <xsl:when test="$items">
            <xsl:variable name="item" select="$items[1]" />
            <xsl:variable name="n" select="substring-before($item, ' ')" />
            <!-- recursive call -->
            <xsl:call-template name="add">
                <xsl:with-param name="items" select="$items[position() > 1]"/>
                <xsl:with-param name="sum" select="$sum + $n"/>
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$sum"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

</xsl:stylesheet>