views:

29

answers:

2

Hi, I have an xml like

<MainNode>
 <Data SubjectID="19233">
  <SubNode CS="100,1" >
   <AB V="PSDF"/>
  </SubNode>
 </Data>
 <Data SubjectID="19234">
  <SubNode  CS="111,1">
   <AB V="PSDF" />
  </SubNode>
 </Data>
</MainNode>

When i try to sum the value of attribute "@CS" i am getting "NaN" as result. Can anyone help me to solve this issue.

Thanks in advance Pradeep

+1  A: 

I think this is overcomplicated, but you could try:

<xsl:template name="sum_helper">
  <xsl:param name="current" select="0" />
  <xsl:param name="rest" /> 
  <xsl:choose>
    <xsl:when test="count($rest) &gt; 0">
      <xsl:call-template name="sum_helper">
        <xsl:with-param name="current"
                        select="$current + translate($rest[1],',','.')" />
        <xsl:with-param name="rest" select="$rest[position()&gt;1]" />
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$current" />
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

   ...
   <xsl:call-template name="sum_helper">
     <xsl:with-param name="rest" select="//SubNode/@CS" />
   </xsl:call-template>
   ...
KennyTM
Thanks Buddy.... its working...... :)
Pradeep
+1  A: 

As an XPath 2.0 one-liner:

sum(/*/*/SubNode/@CS/number(translate(.,',','.')))

An XSLT 2.0 solution:

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
 <xsl:output method="text"/>

 <xsl:template match="/">
   <xsl:value-of select=
   "sum(/*/*/SubNode/@CS/number(translate(.,',','.')))"/>
 </xsl:template>
</xsl:stylesheet>

XSLT 1.0 with FXSL:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:f="http://fxsl.sf.net/"
 xmlns:func-transform="f:func-transform"
 exclude-result-prefixes="xsl f func-transform"
>
   <xsl:import href="transform-and-sum.xsl"/>

   <xsl:output method="text"/>

   <func-transform:func-transform/>

    <xsl:template match="/">
      <xsl:call-template name="transform-and-sum">
        <xsl:with-param name="pFuncTransform" 
                        select="document('')/*/func-transform:*[1]"/>
        <xsl:with-param name="pList" select="/*/*/SubNode/@CS"/>
      </xsl:call-template>
    </xsl:template>

    <xsl:template match="func-transform:*" mode="f:FXSL">
      <xsl:param name="arg1"/>
      <xsl:value-of select="translate($arg1, ',', '.')"/>
    </xsl:template>

</xsl:stylesheet>

When applied on the provided XML document:

<MainNode>
 <Data SubjectID="19233">
  <SubNode CS="100,1" >
   <AB V="PSDF"/>
  </SubNode>
 </Data>
 <Data SubjectID="19234">
  <SubNode  CS="111,1">
   <AB V="PSDF" />
  </SubNode>
 </Data>
</MainNode>

all of these three solutions produce:

211.2
Dimitre Novatchev