XML Formatting: Comments, CDATA, and What "Beautify" Actually Means

By · Published

A JSON formatter has an easy job: whitespace between tokens is never meaningful, so a formatter can throw all of it away and re-indent from scratch with zero risk. XML doesn't give you that guarantee, which is why a naive XML "beautifier" can quietly corrupt a document that looked fine before you ran it.

Whitespace-only text is safe to reformat

Between two sibling elements, as in <a>1</a> <b>2</b>, the newline and spaces are almost always the previous author's indentation. A formatter can drop that whitespace and re-indent cleanly without changing what the document means.

Comments and CDATA have to survive

<!-- ... --> comments and <![CDATA[ ... ]]> sections are content. A formatter that drops a comment on reformat is destroying data, the same as a JSON formatter that deleted a key. It's just less obvious, because the output still "looks like valid XML." CDATA is worse to get wrong. It exists so a payload like <b>hi</b> can sit inside an XML document as literal text instead of being parsed as a nested tag. Re-serializing it through entity-escaping instead of keeping the CDATA wrapper changes what a downstream parser sees.

Self-closing vs. explicit-empty is a notation choice

Advertisement

<empty/> and <empty></empty> are semantically identical to any XML parser. Plenty of formatters normalize one into the other. This tool takes the conservative approach and keeps whichever notation the author used. Formatting fixes indentation and leaves the author's other choices alone.

Entities round-trip through decode, then re-encode

<msg>Tom &amp; Jerry</msg> decodes to the literal text "Tom & Jerry" on parse. A formatter has to re-encode that literal & back to &amp; on the way out. Skip the re-encoding step and the formatted output is no longer valid XML; skip the decoding step on parse and you'll double-escape on every format-reformat cycle.

Mixed content is the hard case

<p>Hello <b>world</b>!</p> has text and elements interleaved in the same parent. That's where whitespace can matter again: a space before <b> is part of the sentence, not indentation. Full HTML/XHTML-style whitespace fidelity for mixed content is out of scope for a general beautifier. If your XML relies on significant whitespace inside mixed content, check the output after reformatting instead of assuming nothing changed.

Advertisement

Try the XML Formatter →