Jump to content
Sign in to follow this  
manus26

XSLT for XML to JSON

Recommended Posts

Need an xslt to convert xml into json.I have a xml file which is having 3 attributes.The value in the 3rd attribute is another xml file.I need an xslt which can read the value of the 3rd attribute as another xml (not just a value) and can convert it into json format. <?xml version="1.0"?> <ResultSet> <attribute1>123</attribute1> <attribute2>456</attribute2> <attribute3> <?xml version="1.0"?> // Need this xml (i.e. value of third attribute) to be converted into Json <NewResultSet> <rowset> <node1>111</node1> <node2>222</node2> </rowset> <rowset> <node1>333</node1> <node2>444</node2> </rowset> </NewResultSet> </attribute3> </ResultSet>

  • Like 1

Share this post


Link to post
Share on other sites

How should the JSON look like? I mean, there isn't a 1:1 mapping between them, so...I'll assume you want every element name to be a JSON name, and every text() node to be a JSON value. In that case, the following should work:

	<xsl:template match="*">		<xsl:if test="not(preceding-sibling::*)">{</xsl:if>"<xsl:value-of select="local-name()"/>": <xsl:apply-templates/>		<xsl:choose>			<xsl:when test="following-sibling::*">,</xsl:when>			<xsl:otherwise>}</xsl:otherwise>		</xsl:choose>	</xsl:template>

However, you may have to remove the XML prolog at the start of attribute3, as some XML parsers don't allow this.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...