jsonix icon indicating copy to clipboard operation
jsonix copied to clipboard

marshalling to string with pretty print

Open br8kpoint opened this issue 6 years ago • 3 comments
trafficstars

As far as I can see, there is no way to marshalString to provide formatted output that would be suitable for saving to a file.

Am I missing something?

br8kpoint avatar Nov 15 '19 15:11 br8kpoint

No, there is no such way at the moment. Jsonix uses XMLSerializer for serialization and it does not support pretty printing.

highsource avatar Nov 15 '19 15:11 highsource

I recently stumbled across this too and was hoping for an easy config option to output a pretty printed string.

Knochenmark avatar Oct 09 '20 08:10 Knochenmark

I've got something of a 'solution'. It's not quite the most pleasant, but it should be quite flexible for any additional changes required (albeit needing those changes to be implemented within an xslt environment)

    var xsltDoc = new DOMParser().parseFromString(
      [
        // describes how we want to modify the XML - indent everything
        "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>",
        "  <xsl:output omit-xml-declaration='no' indent='yes'/>",
        "  <xsl:template match='node()|@*'>",
        "    <xsl:copy>",
        "      <xsl:apply-templates select='node()|@*'/>",
        "    </xsl:copy>",
        "  </xsl:template>",
        "</xsl:stylesheet>",
      ].join("\n"),
      "application/xml"
    );

    var xsltProcessor = new XSLTProcessor();
    xsltProcessor.importStylesheet(xsltDoc);
    var pretty_doc = xsltProcessor.transformToDocument(doc);

One problem is that it will strip out CDATA sections. If you know ahead of time which you want to retain then you can add the following attribute to the xsl:output element cdata-section-elements='elementType1 elementType2 elementType3 ...'

bevanweiss avatar Dec 05 '21 01:12 bevanweiss