I've got a .NET library that uses an XSLT file for transforming beer xml files into json for a web app.
The XSLT file looks a lot like this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" omit-xml-declaration="yes" />
<xsl:template match="RECIPES">
{
{
"description": {
"name": "<xsl:value-of select="NAME"/>",
"style": "<xsl:value-of select="STYLE/NAME"/>",
...
And I'm converting using this piece of code in c#:
using(var writer = new StringWriter()){
_xsltCompiler.Transform(_document, null, writer);
json = writer.ToString();
}
Now, the problem is that curly braces and whitespace is missing from the output. And it used to work. From the source control history I can see no aparent changes lately. Any suggestions on how to fix this?
I would recommend transforming it initially to xml and storing it into a variable then applying a standard/general template to transform that to JSON. I would this this slightly different using XSLT 2.0 or 3.0 and implement xml-to-json()
.
This is my solution to the example above:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" omit-xml-declaration="yes" />
<xsl:template match="RECIPES">
<xsl:variable name="xml">
<description>
<xsl:element name="name">
<xsl:value-of select="NAME"/>
</xsl:element>
<xsl:element name="style">
<xsl:value-of select="STYLE/NAME"/>
</xsl:element>
</description>
</xsl:variable>
{<xsl:apply-templates select="$xml" mode="xml-to-json"/>}
</xsl:template>
<!-- Object or Element Property-->
<xsl:template match="*" mode="xml-to-json">
"<xsl:value-of select="name()"/>" :
<xsl:call-template name="Properties">
<xsl:with-param name="parent" select="'Yes'"></xsl:with-param>
</xsl:call-template>
</xsl:template>
<!-- Array Element -->
<xsl:template match="*" mode="ArrayElement">
<xsl:call-template name="Properties"/>
</xsl:template>
<!-- Object Properties -->
<xsl:template name="Properties">
<xsl:param name="parent"></xsl:param>
<xsl:variable name="childName" select="name(*[1])"/>
<xsl:choose>
<xsl:when test="not(*|@*)">
<xsl:choose>
<xsl:when test="$parent='Yes'">
<xsl:text>"</xsl:text>
<xsl:value-of select="."/>
<xsl:text>"</xsl:text>
</xsl:when>
<xsl:otherwise>"<xsl:value-of select="name()"/>":"<xsl:value-of select="."/>"</xsl:otherwise>
</xsl:choose>
</xsl:when>
<xsl:when test="count(*[name()=$childName]) > 1">{ "<xsl:value-of select="$childName"/>" :[<xsl:apply-templates select="*" mode="ArrayElement"/>] }</xsl:when>
<xsl:otherwise>{<xsl:apply-templates select="@*" mode="xml-to-json"/><xsl:apply-templates select="*" mode="xml-to-json"/>}</xsl:otherwise>
</xsl:choose>
<xsl:if test="following-sibling::*">,</xsl:if>
</xsl:template>
</xsl:stylesheet>