开发者

XSLT: Handling numeric values that use exponent notation

We have to transform some XML that contain numbers in exponent (aka scientific) notation eg.

    <Value>12.34e12</Value>
    <Value>-12.34e-12</Value>

rather irritatingly, we cannot use the sum() function and the like because the XSLT parser expects numbers to be in decimal format.

[We are using the .Net XslCompiledTransform class to do the transform but I think this problem is common to all XSLT implementations]

The only solution to this problem that we have so far is to transform the string value to a number using a javascript function (see below) and then write 开发者_StackOverflowour own sum template which calls this function.

It seems to me that there must be a better way - is there?

/*
 This function attempts to coerce the input into a number. 
*/
function toNumber( x ) {
 if(!x) {
  return Number.NaN;
 }
 if(typeof x === 'number') {
  return x;
 }
 return parseFloat(x);
};


Saxon-B 9.0.0.6 works fine here. Outputs 0.

EDIT: Now I see that Saxon 6 (processor only for xslt 1.0) returns NaN. But if you try xslt 2.0, you won't ever want anything else. :-)

XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <Value>12.34e12</Value>
    <Value>-12.34e12</Value>
</root>

XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="root">
    <xsl:value-of select="sum(Value)"/>
</xsl:template>
</xsl:stylesheet>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜