Search code examples
jsonxmlxslt-2.0

Convert XML to JSON with XSLT 2.0


I have a XSLT that can convert XML to JSON and it works well. But When I'm trying to modify the value type of JSON I'm unable to do so.

Below is my XSLT file code:

<xsl:template match="json:name" mode="json">
    <xsl:text/>"<xsl:value-of select="json:encode-string(.)"/>":<xsl:text/>
</xsl:template>

<xsl:template match="json:value" mode="json">
    <xsl:choose>
        <xsl:when test="node() and not(text())">
            <xsl:apply-templates mode="json"/>
        </xsl:when>
        <xsl:when test="text()">
            <xsl:choose>
                                    <xsl:when test="normalize-space(.) ne . or not((string(.) castable as xs:integer and not(starts-with(string(.),'+') or starts-with(string(.),'-')) and not(starts-with(string(.),'0') and not(. = '0'))) or (string(.) castable as xs:decimal and not(starts-with(string(.),'+')) and not(starts-with(.,'-.')) and not(starts-with(.,'.')) and not(starts-with(.,'-0') and not(starts-with(.,'-0.'))) and not(ends-with(.,'.')) and not(starts-with(.,'0') and not(starts-with(.,'0.'))))) and not(. = 'false') and not(. = 'true') and not(. = 'null')">
                                        <xsl:text/>"<xsl:value-of select="json:encode-string(.)"/>"<xsl:text/>
                                    </xsl:when>
                <xsl:otherwise>
                    <xsl:text/><xsl:value-of select="."/><xsl:text/>
                </xsl:otherwise>

            </xsl:choose>
        </xsl:when>
        <xsl:otherwise>
            <xsl:text>null</xsl:text>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

I want to add a condition that if xml element name is id and it's non-null, then convert it to string.

I tried below thing, but it didn't work.

    <xsl:template match="id">
    <xsl:choose>
        <xsl:when test="id">
            <xsl:text/>"<xsl:value-of select="json:encode-string(.)"/>"<xsl:text/>
        </xsl:when>
    </xsl:choose>
</xsl:template>

How do I iterate over these elements as key-value pair, so I can add conditional logic to value if name matches?

Edit:

Added sample XML:

<?xml version="1.0" encoding="UTF-8"?>
 <ns0:TestMe xmlns:ns0="urn:hero:wakanda:Cle:Something">
   <root>
     <id>123</id>
     <field2>345</field2>
     <fee>
        <totalFee>123</totalFee>
    </fee>
    </root>
    </ns0:TestMe>

Using this XML to JSON converter file: https://github.com/bramstein/xsltjson/blob/master/conf/xml-to-json.xsl


Solution

  • In the context of the stylesheet linked to from your question edit I think you want something like

      <xsl:template match="json:member[json:name = 'id']/json:value" mode="json">
        <xsl:text>"</xsl:text>
        <xsl:value-of select="json:encode-string(.)"/>
        <xsl:text>"</xsl:text>
      </xsl:template>
    

    to get e.g. "id":"123" instead of e.g. "id":123.