Reputation: 388
I have xml that contains special character and i am using xsl to convert this xml to json. However it is generating invalid json with parse error.
here is my input xml-
<?xml version="1.0" encoding="utf-8"?>
<root>
<mydata>
<data1>
<Description>670054 [ CS\48] AGSB ON ROAD</Description>
</data1>
</mydata>
</root>
XSL that i am trying-
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" indent="yes" />
<xsl:template match="/">
{
"Data":[{
"ShortDescription":<xsl:value-of select="root/mydata/data1/Description"/>
}]}
</xsl:stylesheet>
Expected output-
{
"Data":[
{
"Id": "670054",
"ShortDescription": "670054 [ CS\48] AGSB ON ROAD"
]
}
Any help would be appreciated !
Upvotes: 1
Views: 931
Reputation: 388
Here i found one solution to resolve this issue for valid json.
<xsl:template name="handleBackSlash">
<xsl:param name="string" select="."/>
<xsl:choose>
<xsl:when test="contains($string, '\')">
<xsl:value-of select="concat(substring-before($string, '\'), '\\' )"/>
<xsl:call-template name="handleBackSlash">
<xsl:with-param name="string" select="substring-after($string, '\')"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$string"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
then call template-
<xsl:call-template name="handleBackSlash">
<xsl:with-param name="string" select="Description"/>
</xsl:call-template>
Upvotes: 0
Reputation: 163360
XSLT 3.0 includes functionality to output JSON. In earlier versions you can do it "by hand" using the text output method, which is what you are doing here. But then it's entirely your responsibility to format the output JSON correctly, including in particular escaping of special characters such as quotes, newlines, and backslashes. That's easy enough in XSLT 2.0 using the replace() function; it's rather more convoluted in XSLT 1.0, though exslt.org has some templates you can incorporate into your stylesheet, such as str:replace.
When you ask questions about XSLT on this site, do please say which XSLT version(s) you are able to use. It often makes a difference to the answer. The problem is that XSLT 1.0 is now very old, but (like COBOL) many people still seem to be using it.
Upvotes: 1