0

I have a XML document that I want to serialize with proper indentation. I have seen this post, however all proposed answers have flaws:

  • Some answers use a XSLT transformation with the <xsl:output indent="yes"/> tag, however there are some drawbacks to this solution. Firstly, it does not work on browsers like Firefox. Secondly, it does not correctly indent processing instructions (such as <?xml-model ...?>). Finally, it omits the <?xml version="1.0" encoding="UTF-8"?> declaration at the beginning, and I would like to keep it if possible.

  • Some other answers use regex or custom parsing of the XML, however it is widely considered to be an anti-pattern.

  • Finally, some answers rely on a third-party library, but I find it overkill to use a library (that is sometimes poorly maintained) to do such a simple task.

Is there a cross-compatible, library-free and regex-free solution to serialize a Javascript XML document into a properly indented string?

Thank you for your help.

JacopoStanchi
  • 1,646
  • 4
  • 28
  • 55
  • Library free will be next to impossible, cross-compatible might be to rely on XPath 3.1 `serialize` function as implement for instance by the Saxon-JS 2 runtime for both clients-side JavaScript as well as Node.js or its `serialize` API https://www.saxonica.com/saxon-js/documentation/index.html#!api/serialize. It allows you to use some options as defined for XDM serialization. But in the end "properly indented" is underdefined and some stuff like DTDs/Doctype are ignored by XDM based solutions. – Martin Honnen Aug 16 '21 at 13:45

0 Answers0