How to Format and Pretty-Print XML
How to pretty-print XML without changing its data. We ran our formatter on seven risky documents (mixed content, xml:space, CDATA, namespaces, SVG text) and re-parsed the results: all seven kept identical data.
Why Format XML
Feeds, sitemaps, SOAP responses, SVG exports and Office files (a .docx is a ZIP of XML parts) often arrive as one long line. Indentation shows the nesting, which is what you need to find an element, spot a misplaced closing tag or diff two versions.
Pretty-Printing Without Changing the Data
Formatting adds whitespace between elements. Most of the time that whitespace is meaningless, but XML 1.0 says a parser must pass all text, including whitespace, on to the application, so a careless formatter can change content. The risky cases are mixed content (text and elements together, as in SVG <text> or XHTML paragraphs), elements marked xml:space="preserve", and CDATA sections.
We ran the XML Formatter's own serializer in Chromium on seven such documents and re-parsed every result with lxml, comparing it with the input after removing whitespace-only text (October 13, 2026; cases and script in our test folder):
| Case | What the formatter did | Same data? |
|---|---|---|
Mixed content: <p>Hello <b>world</b>, and <i>you</i>!</p> | kept the paragraph on one line | yes |
xml:space="preserve" with leading spaces and a line break | left the element's content untouched | yes |
| CDATA, a comment and a processing instruction | kept all three as written | yes |
| Entities and quotes in text and attributes | re-escaped them correctly | yes |
| Default and prefixed namespaces | kept both declarations and prefixes | yes |
SVG <text> with an inline <tspan> | kept it inline (spaces around B survive) | yes |
| RSS item with escaped HTML in the description | indented, escaping unchanged | yes |
All seven came back with an identical element tree, attributes and text, and the output was character-for-character identical to xmllint --format (libxml2 2.9) on all seven, apart from xmllint adding an XML declaration. If you use another formatter, test it on a mixed-content sample first: a formatter that puts <b>world</b> on its own line has changed the text.
The Errors That Stop a Parser
XML parsers must stop at the first well-formedness error rather than guess. The usual culprits:
- Unclosed or mismatched tags. Names are case-sensitive, so
<Title>is not closed by</title>. - Bare ampersands and angle brackets in text. Write
&and<; only five entities are predefined (<,>,&,',"), so HTML entities such as are errors unless the document declares them. - Overlapping elements such as
<b><i>x</b></i>. - More than one root element, or text outside the root.
- Anything before the XML declaration, even a blank line, when a declaration is present.
The formatter reports the parser's error instead of formatting a broken document. The options it does have are indentation (2 spaces, 4 spaces or tabs), minify, and syntax highlighting.