XSLT3 - xml-to-json() function generate un-escaped json

201 Views Asked by At

Using Saxon XSLT 3.0 I am trying to convert XML to JSON. The first step is to convert the input XML into the required Maps & Array format the xml-to-json() required format.

When I then call the function with

<xsl:result-document href="{$target_json}" method="json">
    <xsl:copy-of select="xml-to-json($intermediate_XML, map{., 'indent':false() })"></xsl:copy-of>
</xsl:result-document>  
        

Sample XML:

<?xml version="1.0" encoding="US-ASCII"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
   <string key="headline">Matilda sold such dreadful ties</string>
   <string key="body">
&lt;p&gt;Matilda sold such dreadful ties.&lt;/p&gt;
&lt;p&gt;It made Juan retch and...&lt;/p&gt;
</string>
</map>

JSON Result

"\n { \"headline\" : \"Matilda sold such dreadful ties\",\n \"body\" : \"\\n<p>Matilda sold such dreadful ties.<\\\/p>\\n<p>It made Juan retch and...<\\\/p>\\n\" }"

What I expected and need is

{ "headline" : "Matilda sold such dreadful ties", "body" : "\n<p>Matilda sold such dreadful ties.<\/p>\n<p>It made Juan retch and...<\/p>\n" }

Without the Starting and ending quote " and all the escaped characters.

Any assistance would be most welcome, thanks.

1

There are 1 best solutions below

2
Martin Honnen On

I don't think you want both output method as json and also use xml-to-json, use output method text for the result of that function.

Example using Saxon HE 11.

Another example using Saxon HE 11 in an Azure backend, this time with xsl:result-document.

The output method json is useful if you represent your data as XDM 3.1 maps/arrays e.g.

<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">

  <xsl:output method="json" indent="yes"/>

  <xsl:template name="xsl:initial-template">
    <xsl:sequence
      select='map { "headline" : "Matilda sold such dreadful ties", "body" : "&#10;&lt;p>Matilda sold such dreadful ties.&lt;/p>&#10;&lt;p>It made Juan retch and...&lt;/p>&#10;" }'/>
  </xsl:template>

</xsl:stylesheet>

Online example.