Govind
Govind

Reputation: 979

Convert string type number to int number and sum up in XSLT 1.0

I have below XML,

    <Answers>
     <Entry key="total" type="System.String">
      <value>50,000</value>
     </Entry>
    </Answers>
    <Answers>
     <Entry key="total" type="System.String">
      <value>2,000</value>
     </Entry>
    </Answers>
    <PerPersonTotal>1000</PerPersonTotal>

In XSLT 1.0 i have to sum up all the values and calculate percentage.

Note that the amount value has comma.

<xsl:value-of select="(PerPersonTotal div sum(number(Answers/Entry[@key='total']/value))) * 100

and am getting below error

Argument 1 of function 'sum()' cannot be converted to a node-set.

if i remove number function i am getting NaN as result.

Upvotes: 2

Views: 4946

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117073

Note that the amount value has comma.

And that's exactly the problem here: a string containing a comma is not a number. To solve this in XSLT 1.0, you will need to do something like:

<xsl:variable name="values">
    <xsl:for-each select="Answers/Entry[@key='total']">
        <value>
            <xsl:value-of select="translate(value, ',', '')"/>
        </value>
    </xsl:for-each>
</xsl:variable>
<result>
    <xsl:value-of select="PerPersonTotal div sum(exsl:node-set($values)/value)"/>
</result>

after declaring xmlns:exsl="http://exslt.org/common" - see: http://exslt.org/exsl/index.html

Note:

  1. This assumes the comma here is used as a thousands separator;
  2. To format a number as percentage, you should use the format-number() function, not multiply by 100.

Upvotes: 0

Related Questions