What the formatter does to your XML
Formatting changes only the whitespace between tags. Given a single-line document like this:
<?xml version="1.0"?><catalog><book id="bk101"><author>Gambardella, Matthew</author><title>XML Developer's Guide</title><discontinued/></book></catalog>you get:
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<discontinued/>
</book>
</catalog>- Each element starts on its own line, indented one level deeper than its parent.
- Elements that contain only a short piece of text stay on one line.
- Attributes stay in the order you wrote them; extra spaces between attributes are collapsed.
- Comments,
<![CDATA[ ... ]]>sections,<?xml ... ?>declarations and<!DOCTYPE>are kept verbatim.
Common reasons XML will not format
A formatter can only indent XML that parses. These are the errors people hit most often:
- Unclosed or mismatched tags —
<b><i>text</b></i>closes in the wrong order. - An unescaped ampersand — write
&instead of a bare&in text and attribute values. - More than one root element — wrap sibling top-level elements in a single parent.
- Unquoted attribute values —
id=5must beid="5". - Text before the XML declaration —
<?xml ... ?>must be the very first thing in the file.
Format XML from the command line, Python or VS Code
# Linux / macOS (libxml2)
xmllint --format input.xml > pretty.xml# Python standard library
from xml.dom import minidom
print(minidom.parseString(open("input.xml").read()).toprettyxml(indent=" "))// Node.js — prettier with @prettier/plugin-xml
npx prettier --plugin=@prettier/plugin-xml --write input.xmlIn VS Code, install Red Hat's XML extension and run Format Document. For a one-off file, pasting it here is faster.
Working with XML and JSON
Need the data as JSON instead? Use the XML to JSON converter, or go the other way with JSON to XML. For JSON itself, the JSON formatter does the same job as this page.