How to avoid solidus and double quote escaping of XML in JSON?
Given that
- solidus characters (aka forward slash,
/
) may, but need not, be escaped in JSON, and that - XML attributes may use
'
rather than"
to avoid escaping in JSON string values,
what's the best way to realize these potential serialization improvements in XSLT?
This XML,
<?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
<array key="o_array">
<map>
<string key="s/1">x/y/z</string>
</map>
<map>
<string key="s2"><![CDATA[<a href="/x/y">Link</a> a/b "test"]]></string>
</map>
</array>
</map>
input to this XSLT,
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:value-of select="xml-to-json(.,map{'indent':true()})"/>
</xsl:template>
</xsl:stylesheet>
yields (via Saxon, XSLT Fiddle demo) this JSON output:
{ "o_array" :
[
{ "s\/1" : "x\/y\/z" },
{ "s2" : "<a href=\"\/x\/y\">Link<\/a> a\/b \"test\"" } ] }
For purposes of aesthetics (above JSON is unnecessarily ugly) and minimizing file size (after also disabling indentation), I would like to be generating the following JSON instead:
{ "o_array" :
[
{ "s/1" : "x/y/z" },
{ "s2" : "<a href='/x/y'>Link</a> a/b \"test\"" } ] }
Notes:
- Single quotes: A Saxon-specific serialization option,
saxon:single-quotes
, seems tantalizing close to helping, but how to use this option withxml-to-json()
is unclear to me. - Solidus: An XSLT serialization option,
map{'method': 'json', 'use-character-maps': map{ '/': '/' }}
as described by Martin Honnen, seems tantalizing close to helping, but, again, how to use this option withxml-to-json()
escapes (ha) me. string/@escape
andstring/@escape-key
attributes, per my reading of the spec and confirmed via experimentation, cannot help here.