Search code examples
xmlxsltxslt-1.0

Convert an xml(with a json) to a json response using xslt 1.0


I have a request xml which has a json -> which I want to map into another json using xslt. I am using xslt 1.0. Is there a way i can achieve this in xslt 1.0: The request xml is:

<root> { "id": 5656, "country-name": "country-text" } <root>

the response that i need to map to:

{ "mid": 5656, "cid" : "country-text" }

Please assist

I tried a few methods, was able to copy the source json into the final response - but that does not help as i need to read individual fields and map them to different keys

With the method i tried -> i was able to get {id:5656, country-name:'country-text' }

what i want is :

{ mid: 5656, cid : 'country-text' }


Solution

  • I suppose this is one way you could look at it:

    XSLT 1.0

    <xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" encoding="UTF-8"/>
    
    <xsl:template match="/root">
        <xsl:text>{ mid: </xsl:text>
        <xsl:value-of select="substring-before(substring-after(., '&quot;id&quot;: '), ',')" />
        <xsl:text>, cid : </xsl:text>
        <xsl:value-of select="substring-before(substring-after(., '&quot;country-name&quot;: '), ' }')" />
        <xsl:text> }</xsl:text>
    </xsl:template>
    
    </xsl:stylesheet>
    

    Note that this assumes that country-name is always the last pair in the JSON object, and id is not.