Search code examples
jsonnumber-formattingxslt-3.0

xslt 3.0 xml to JSON number format


I would like to convert the following xml to JSON:

<?xml version='1.0' encoding='utf-8'?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
    <array key="ids">
        <number>3218087</number>
    </array>
</map>

using

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">

    <xsl:output method="text" />

    <xsl:template match="/">
        <xsl:value-of select="xml-to-json(.)" />
    </xsl:template>

</xsl:stylesheet>

This gives me:

{"ids":[3.218087E6]}

What I need is

{"ids":[3218087]}

Any help would be highly appreciated.

Cheers Przemek


Solution

  • The spec https://www.w3.org/TR/xpath-functions/#func-xml-to-json for a number element suggests:

    An element $E named number results in the output of the string result of xs:string(xs:double(fn:string($E)))

    and the cast to xs:string requires the E notation for values greater than 1000000 I think (https://www.w3.org/TR/xpath-functions/#casting-to-string).

    So I don't think the xml-to-json result can be changed, unless a processor allows some options to choose a different formatting rule for numbers.