highsource / jsonix

Powerful XML<->JSON JavaScript mapping library.
BSD 2-Clause "Simplified" License
356 stars 75 forks source link

marshalling to string with pretty print #235

Open br8kpoint opened 4 years ago

br8kpoint commented 4 years ago

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?

highsource commented 4 years ago

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

Knochenmark commented 3 years ago

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

bevanweiss commented 2 years ago

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 ...'