简体   繁体   中英

How to add decimal numbers in xslt 1.0 in substrings

I have the following input xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<values>
    <value>sometext;+123.23;+100.23</value>
    <value>sometext;+004.23;+444.12</value>
</values>

I am a newbie in XSL 1.0. I would like to add two decimal numbers received in strings but I am receiving NaN error. How do I do that. I would like to get the following output from the above input xml where the decimal values are summed but instead I am receiving NaN errors.

<?xml version="1.0"?>
<Results>
    <Result>+223.46</Result>
    <Result>+448.35</Result>
</Results>

I have the XSL file as follows,

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match = "/"> 
<Results>
<xsl:for-each select="values/value">
  <Result>
     <xsl:value-of select="number(substring(.,10,7)) + 
   number(substring(.,18,7))" />
  </Result>
</xsl:for-each>
</Results>
</xsl:template>

A number is not allowed to contain a + sign.

Try instead:

<xsl:value-of select="substring(., 11, 6) + substring(., 19, 6)" />

(assuming of course that the positions and lengths are constant - and that the numbers are always positive).


My own preference would be to do:

XSLT 1.0

<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="/values"> 
    <Results>
        <xsl:for-each select="value">
            <xsl:variable name="a" select="substring-before(substring-after(., ';'), ';')" />
            <xsl:variable name="b" select="substring-after(substring-after(., ';'), ';')" />
            <Result>
                <xsl:value-of select="translate($a, '+', '') + translate($b, '+', '')" />
            </Result>
        </xsl:for-each>
    </Results>
</xsl:template>

</xsl:stylesheet>

which will work with positive and negative numbers alike, and does not depend on the length of any one of the three tokens in the given string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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