← All guides

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

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 — <a>1</a> <b>2</b> — the newline and spaces are almost always just the previous author's indentation, not content. 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 real content, not formatting noise. A formatter that silently drops a comment on reformat is destroying data the same way a formatter that deletes a JSON key would be — it just looks less obviously wrong because the output still "looks like valid XML." CDATA is worse to get wrong: it exists specifically 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

<empty/> and <empty></empty> are semantically identical to any XML parser. Plenty of formatters normalize one into the other. A more conservative approach — the one this tool takes — is to preserve whichever notation the author used: formatting should fix indentation, not rewrite choices that didn't need fixing.

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 genuinely hard case

<p>Hello <b>world</b>!</p> — text and elements interleaved in the same parent — is where whitespace can become meaningful 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 leans on significant whitespace inside mixed content, treat automatic reformatting as a starting point to check, not a guaranteed no-op.

Try the XML Formatter