Reputation: 179
I find it very hard to find good example on the internet to transform a simple json to xml using xslt3 with the SaxonJS library. I found the following: https://www.saxonica.com/papers/xmlprague-2016mhk.pdf But I can not really follow how that works.
I've tried running:
npm i xslt3
./node_modules/.bin/xslt3 -json:test.json -xsl:test.xsl -o:test.xml -t && cat test.xml
With example JSON:
{
"a": 1
}
With XSL:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
version="3.0">
<xsl:template match="/">
<base>
<a>
<xsl:value-of select="/map/number"/>
</a>
</base>
</xsl:template>
</xsl:stylesheet>
But this leads to an empty XML.
Also changing the select to:
<xsl:template match=".">
<base>
<a>{?a}</a>
</base>
</xsl:template>
as suggested by other items don't seem to work. Not sure if this is related to the latest version. I'm using version 2.7.0
Upvotes: 2
Views: 63
Reputation: 167506
It is not clear which XSLT format/result you want but if you use the -json
option then the JSON is represented as an XDM 3.1/XPath 3.1 map and/or array and subsequently your second approach using the lookup operator ?
seems like the right approach.
With complete context:
XSLT
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="3.0"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="#all"
expand-text="yes">
<xsl:template match=".">
<base>
<a>{?a}</a>
</base>
</xsl:template>
</xsl:stylesheet>
transforms JSON
{
"a": 1
}
into XML
<?xml version="1.0" encoding="UTF-8"?><base><a>1</a></base>
Works fine for me in my fiddle as well as from the command line:
As for using json-to-xml
, in that case I would start with the initial template named xsl:initial-template
, use a global parameter for the JSON file name (or URI in general), read the JSON as a string with unparsed-text
and then convert to XML, pushing the result to your templates that transform the XML representation of the JSON to the XML format you want. Keep in mind that the result elements of json-to-xml
are in the XPath function namespace.
Example stylesheet:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xpath-default-namespace="http://www.w3.org/2005/xpath-functions"
version="3.0"
exclude-result-prefixes="#all">
<xsl:param name="json-uri" as="xs:string">sample1.json</xsl:param>
<xsl:template name="xsl:initial-template">
<xsl:apply-templates select="$json-uri => unparsed-text() => json-to-xml()"/>
</xsl:template>
<xsl:template match="/">
<base>
<a>
<xsl:value-of select="/map/number[@key = 'a']"/>
</a>
</base>
</xsl:template>
</xsl:stylesheet>
Example run:
Upvotes: 1