Jump to content

XSLT for XML to JSON


manus26

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
Link to comment
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.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...