Skip to content
uencoder
TUTORIAL

How to Format and Beautify XML

Transform compact XML into a readable, indented format with proper nesting.

Problem

Your XML is minified or inconsistently indented, making it hard to read and debug.

Prerequisites

  • Understanding of XML structure
  • Familiarity with tree-based markup

Steps

  1. 1. Validate the XML

    Before formatting, ensure the XML is well-formed: all tags are closed, attributes are quoted, and there is a single root element. Malformed XML cannot be reliably formatted.

    Input
    <root><item>text</item></root>
    Output
    well-formed
  2. 2. Apply indentation and line breaks

    Add a newline after each element and indent child elements relative to their parent. Use a consistent indent size (2 or 4 spaces). Self-closing tags and text content should be handled appropriately.

    Input
    <root><item>text</item></root>
    Output
    <root>\n  <item>text</item>\n</root>
  3. 3. Preserve significant whitespace

    XML has both significant and insignificant whitespace. Elements with xml:space="preserve" or mixed content must keep their whitespace. A good formatter respects these rules and does not alter significant whitespace.

    Input
    formatted XML
    Output
    readable, whitespace preserved

Expected result

A well-formed, consistently indented XML document that is easy to read and edit.

Common errors

Formatting breaks mixed content
Mixed content (text interspersed with elements, as in XHTML) has significant whitespace. Use a formatter that preserves mixed content whitespace.
Output is not well-formed
The input XML had errors. Fix the source XML before formatting.

Troubleshooting

  • If the formatter changes the meaning of the document, check whether it normalized whitespace in a preserve context.
  • Use an XML validator first if the formatter fails.

Security limits

  • Formatting does not execute XML. However, parsing XML with DTD enabled can trigger XXE attacks. Use a safe parser.

Related tools

Related tasks

Ready to run it?

References