Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using XSLT to convert XML to JSON

JSON

Using XSLT to convert XML to JSON

by  k5tm  Posted    (Edited  )
In faq1600-6410 the author teaches a method for converting a VBScript (ASP) recordset object to JSON.

It is relatively simple to convert an XML document to JSON on the server side (at the cost of some processing time on the server), thereby possibly simplifying the Javascript in the client.

Here is an XML document containing data similar to that found in faq1600-6409. [code XML]<?xml version="1.0"?>
<root>
<record>
<name handle="tsdragon">
<first>Tracy</first>
<last>Dryden</last>
</name>
</record>
<record>
<name handle="steved">
<first>Steven</first>
<last>Dee</last>
</name>
</record>
<record>
<name handle="thealias">
<first>John</first>
<last>Smith</last>
</name>
</record>
</root>[/code]
Here is an XSLT (translating stylesheet) to convert such a document to JSON suitable for sending to the client:[code XSLT]<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:eek:utput method="text" encoding="UTF-8"/>

<xsl:template match="/">
<xsl:variable name="countNames" select="count(root/record/name)"/>
<xsl:text>( { "Records": [
</xsl:text>
<xsl:for-each select="root/record/name">
<xsl:text>{ "firstname":"</xsl:text>
<xsl:value-of select="first"/>
<xsl:text>","lastname":"</xsl:text>
<xsl:value-of select="last"/>
<xsl:text>","handle":"</xsl:text>
<xsl:value-of select="@handle"/>
<xsl:text>"}</xsl:text>
<xsl:choose>
<xsl:when test="position() &lt; $countNames"><xsl:text>,
</xsl:text></xsl:when>
<xsl:eek:therwise>
<xsl:text>
</xsl:text></xsl:eek:therwise>
</xsl:choose>
</xsl:for-each>
<xsl:text> ],
"RecordCount":"</xsl:text><xsl:value-of select="$countNames"/><xsl:text>" }
) </xsl:text>
</xsl:template>

</xsl:stylesheet>[/code]

Applying the stylesheet to the XML document produces this result:[code JSON]

( { "Records": [
{ "firstname":"Tracy","lastname":"Dryden","handle":"tsdragon"},
{ "firstname":"Steven","lastname":"Dee","handle":"steved"},
{ "firstname":"John","lastname":"Smith","handle":"thealias"}
],
"RecordCount":"3" }
)[/code]
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top