XML Formatter
Format and beautify XML documents with proper indentation and structure.
Input XML
Formatted XML
<?xml version="1.0"?>
<catalog>
<book id="1">
<title>XML Developer's Guide
</title>
<author>John Doe
</author>
<price>44.95
</price>
</book>
<book id="2">
<title>Advanced XML
</title>
<author>Jane Smith
</author>
<price>39.95
</price>
</book>
</catalog>Minified XML
<?xml version="1.0"?><catalog><book id="1"><title>XML Developer's Guide</title><author>John Doe</author><price>44.95</price></book><book id="2"><title>Advanced XML</title><author>Jane Smith</author><price>39.95</price></book></catalog>Tip: Well-formatted XML is easier to read and debug. Minified XML reduces file size for production use.
What Is XML Formatting?
XML (Extensible Markup Language) is a widely used standard for encoding structured data in a human-readable and machine-readable format. When XML is generated programmatically, transmitted over a network, or stored in a database, it is often compacted into a single long line to save space. While this minified form is efficient for machines, it is extremely difficult for developers, data architects, and system integrators to read or debug.
XML formatting — also called XML beautification or pretty-printing — is the process of taking raw, flat XML and restructuring it with consistent indentation and line breaks so that every nested element is clearly visible. A well-formatted XML document allows you to instantly see the parent-child relationships between elements, spot missing closing tags, and identify misplaced attributes without needing a dedicated XML editor.
This online XML formatter takes your pasted or typed XML input and applies a token-based indentation algorithm to produce a cleanly indented version. You can choose an indent size of 2, 4, or 8 spaces depending on your coding style or team conventions. The tool also generates a minified version — stripping unnecessary whitespace between tags — which is useful when you need to embed XML in a configuration file, API payload, or JavaScript string.
XML is used across a huge range of applications: RSS and Atom feeds, SOAP web services, Android layout files, Microsoft Office Open XML (DOCX, XLSX), SVG graphics, Maven build files, Spring Framework configuration, and more. In all of these contexts, the ability to quickly format raw XML and make it readable is an essential developer productivity skill.
How the XML Formatter Works
The formatter uses a token-splitting algorithm that walks through the XML character-by-character at the tag level. The input string is first normalized by collapsing any existing whitespace between adjacent tags, ensuring a consistent starting point regardless of how the original XML was indented. The cleaned string is then split into a sequence of tokens — either XML tags (anything wrapped in angle brackets) or plain text content between tags.
Each token is classified into one of four categories and handled according to a set of indentation rules driven by a running indent level counter:
- Opening tags (
<element>): Output at the current indent level, then increment the indent level by one. - Closing tags (
</element>): Decrement the indent level first, then output at the new (lower) level. - Self-closing tags (
<element />): Output at the current indent level with no change to the indent counter. - Declarations and comments (
<?xml ...?>,<!-- ... -->,<!DOCTYPE ...>): Output at the root level with no indentation changes. - Text content: Trimmed of surrounding whitespace and appended directly to the previous line, keeping element content inline with its opening tag.
The indentation string is computed once as spaces = ' '.repeat(indentSize) and then repeated for each level. This makes the algorithm efficient: at any point the leading whitespace is simply spaces.repeat(indent_level). After processing all tokens, the final output is trimmed of any leading or trailing newlines.
Minification works by a simpler two-step regex pass: first, all whitespace sequences between a closing and an opening angle bracket are collapsed to nothing (><), and then all remaining whitespace runs are collapsed to a single space. This removes formatting whitespace while preserving meaningful text content inside elements.
Indentation Rule
Where:
- indentSize= Number of spaces per indent level (2, 4, or 8)
- indent_level= Current nesting depth, starting at 0 for root elements
- leading_whitespace= The string of spaces prepended to each tag on output
XML Syntax Rules and Structure
Before formatting XML, it helps to understand the core syntax rules that all valid XML must follow. Unlike HTML, XML is case-sensitive and strictly hierarchical — every document must have exactly one root element, and every opened tag must be properly closed.
- Declaration: Most XML documents begin with
<?xml version="1.0" encoding="UTF-8"?>. This is optional but recommended for clarity about the version and character encoding. - Single root element: All content must be wrapped in one top-level element (e.g.,
<root>...</root>). Multiple root elements will cause parsers to throw errors. - Proper tag closure: Every element tag must be closed, either with a matching closing tag (
</name>) or as a self-closing tag (<name />). - Attribute quoting: All attribute values must be enclosed in single or double quotes. Unquoted attributes are not permitted.
- No overlapping tags: Elements must be properly nested.
<a><b></a></b>is invalid; the inner element must close before the outer one. - Reserved characters: The characters
<,>,&,', and"inside text content or attributes must be escaped as XML entities:<,>,&,', and"respectively.
Well-formed XML that follows all structural rules will be successfully formatted by this tool. If your XML contains syntax errors — unclosed tags, missing quotes, unescaped ampersands — the formatter will still attempt to process the input but the output may not reflect the intended structure. Always validate critical XML against an XSD schema or a dedicated XML validator after formatting.
Formatted vs Minified XML: When to Use Each
XML formatting and XML minification are two opposite transformations, and each serves a distinct purpose. Knowing when to apply each is an important part of working with XML-based systems.
| Aspect | Formatted XML | Minified XML |
|---|---|---|
| Readability | High — each element on its own line | Low — one long continuous string |
| File size | Larger due to whitespace and newlines | Smaller — all unnecessary spaces removed |
| Best for | Development, debugging, code review | Production APIs, storage, transmission |
| Network transfer | Slower (more bytes) | Faster (fewer bytes) |
| Version control diffs | Clean line-by-line diffs | Single-line diffs, hard to review |
As a general rule, keep your source XML files formatted for version control and human review, but strip whitespace when embedding XML in API requests, config strings, or anywhere that byte count matters. Many CI/CD pipelines automate this transformation: the repository holds the formatted version, and a build step minifies it for deployment.
Common XML Use Cases and Ecosystems
XML remains one of the most widely deployed data formats in enterprise software, even as JSON has taken over much of the web API space. Understanding where XML is still dominant helps explain why a reliable XML formatter is such a frequently needed tool.
- SOAP web services: Enterprise integrations, banking systems, and legacy ERP platforms often expose SOAP APIs that exchange XML envelopes. Formatting a SOAP response is the first step in debugging an integration failure.
- Android layouts: Android UI is defined in XML layout files. Developers format these regularly to keep them readable as view hierarchies grow deep.
- Maven and Gradle (POM files): Java build configuration in Maven is written in XML (
pom.xml). Proper indentation is essential for managing complex multi-module projects. - RSS and Atom feeds: Content syndication feeds are XML documents. Publishers and aggregators frequently need to inspect or modify feed XML, making formatting indispensable.
- SVG graphics: Scalable Vector Graphics are XML-based. Hand-editing SVG paths and attributes is far easier in a formatted document than in a minified one.
- Office Open XML: Microsoft Word (
.docx), Excel (.xlsx), and PowerPoint (.pptx) files are ZIP archives containing XML. Developers who work with these formats programmatically rely on XML formatters to inspect the underlying markup. - Spring Framework and Java EE: Older Spring configurations and Java EE deployment descriptors (
web.xml,beans.xml) are written in XML, and these files can become deeply nested and hard to navigate without careful formatting.
In all of these ecosystems, the workflow is the same: receive or open a compact XML document, paste it into an XML formatter to understand the structure, make changes in the formatted view, then copy the result back. This tool speeds up that workflow by combining the formatted and minified outputs in one place.
Choosing the Right Indent Size
The indent size you choose for XML formatting is largely a matter of convention and readability preference. This formatter supports 2, 4, and 8 spaces. Here is how each is typically used in practice:
- 2 spaces: Preferred in web development contexts and for XML files that will be stored in version control. The compact indentation keeps lines short even in deeply nested structures, which is important in Android layouts or SOAP envelopes where nesting can exceed 10 levels.
- 4 spaces: The most common standard in Java and .NET ecosystems, where XML configuration files (Spring, Maven, MSBuild) have traditionally used 4-space indentation. It provides a clear visual separation between levels without being as wide as 8 spaces.
- 8 spaces: Sometimes used in documentation or presentation contexts where maximum visual clarity is needed, and when the XML is shallow enough that long lines are not a concern.
Most teams codify their XML indentation preference in an .editorconfig file or in their IDE settings so that all contributors produce consistent formatting. If you are unsure which to choose, 2 spaces is the safest default for modern development workflows, while 4 spaces aligns with traditional enterprise Java conventions.
Worked Examples
Format a Simple Book Catalog (2-space indent)
Problem:
Format the following compact XML with 2-space indentation: `<?xml version="1.0"?><catalog><book id="1"><title>XML Guide</title><price>44.95</price></book></catalog>`
Solution Steps:
- 1Step 1 — Normalize: remove whitespace between tags. The input has none, so it stays as-is.
- 2Step 2 — Tokenize: split on tag boundaries → [`<?xml version="1.0"?>`, `<catalog>`, `<book id="1">`, `<title>`, `XML Guide`, `</title>`, `<price>`, `44.95`, `</price>`, `</book>`, `</catalog>`].
- 3Step 3 — Walk tokens with indent_level=0, spaces=' ' (2 spaces): `<?xml version="1.0"?>` is a declaration → output at column 0, level stays 0. `<catalog>` is opening → output at level 0, level becomes 1. `<book id="1">` is opening → output indented 2 spaces (level 1), level becomes 2. `<title>` is opening → output indented 4 spaces (level 2), level becomes 3.
- 4Step 4 — Text token `XML Guide`: trim, append to previous line → ` <title>XML Guide`. Closing `</title>`: level-- = 2, output indented 4 spaces.
- 5Step 5 — Similarly process `<price>44.95</price>`, then `</book>` (level 1 → 0 indent), then `</catalog>` (level 0). Final trimmed output: ``` <?xml version="1.0"?> <catalog> <book id="1"> <title>XML Guide </title> <price>44.95 </price> </book> </catalog> ```
Result:
Formatted XML with 2-space indentation. Declaration at column 0; each nested element indented by 2 additional spaces; text content appended inline to its opening tag.
Minify an RSS Feed Entry
Problem:
Minify the following formatted XML to a single compact line: ``` <item> <title>Hello World</title> <link>https://example.com</link> <pubDate>2026-06-01</pubDate> </item> ```
Solution Steps:
- 1Step 1 — Apply first regex: replace `>\s+<` (any whitespace between `>` and `<`) with `><`. This collapses all newlines and spaces between adjacent tags. `<item>\n <title>` becomes `<item><title>`, and so on.
- 2Step 2 — Apply second regex: replace any remaining whitespace run (`\s+`) with a single space. This handles any trailing space or space within text content.
- 3Step 3 — Trim the result of any leading/trailing whitespace.
- 4Result after step 1: `<item><title>Hello World</title><link>https://example.com</link><pubDate>2026-06-01</pubDate></item>`
Result:
`<item><title>Hello World</title><link>https://example.com</link><pubDate>2026-06-01</pubDate></item>` — all whitespace between tags removed, single continuous line.
Format XML with Self-Closing Tags (4-space indent)
Problem:
Format the following XML that contains a self-closing element: `<config><server host="localhost" port="8080" /><debug enabled="true" /></config>`
Solution Steps:
- 1Step 1 — Normalize: no whitespace between tags, nothing to change.
- 2Step 2 — Tokenize: [`<config>`, `<server host="localhost" port="8080" />`, `<debug enabled="true" />`, `</config>`].
- 3Step 3 — Walk tokens with indent_level=0, spaces=' ' (4 spaces): `<config>` is opening → output at level 0, level becomes 1.
- 4Step 4 — `<server host="localhost" port="8080" />` ends with `/>` → self-closing. Output indented 4 spaces (level 1), level stays at 1. Same for `<debug enabled="true" />`.
- 5Step 5 — `</config>` is closing → level-- = 0, output at column 0. Final result: ``` <config> <server host="localhost" port="8080" /> <debug enabled="true" /> </config> ```
Result:
Self-closing tags (`/>`) are indented at their nesting level with no change to the indent counter, since they have no children and no matching closing tag.
Format Deeply Nested SOAP-Style XML (4-space indent)
Problem:
Format a compact SOAP-like envelope: `<Envelope><Body><GetUser><id>42</id></GetUser></Body></Envelope>`
Solution Steps:
- 1Step 1 — Normalize: no whitespace between tags, nothing to change.
- 2Step 2 — Tokenize: [`<Envelope>`, `<Body>`, `<GetUser>`, `<id>`, `42`, `</id>`, `</GetUser>`, `</Body>`, `</Envelope>`].
- 3Step 3 — Process: `<Envelope>` at level 0 → level becomes 1. `<Body>` at level 1 (4 spaces) → level becomes 2. `<GetUser>` at level 2 (8 spaces) → level becomes 3. `<id>` at level 3 (12 spaces) → level becomes 4.
- 4Step 4 — Text `42`: append to previous line → ` <id>42`. Then `</id>`: level-- = 3, output at 12 spaces.
- 5Step 5 — `</GetUser>`: level-- = 2, output at 8 spaces. `</Body>`: level-- = 1, output at 4 spaces. `</Envelope>`: level-- = 0, output at column 0.
Result:
``` <Envelope> <Body> <GetUser> <id>42 </id> </GetUser> </Body> </Envelope> ``` — each level adds 4 spaces; deeply nested elements are clearly visible.
Tips & Best Practices
- ✓Paste minified XML from API responses or log files into the formatter immediately to make the structure readable before debugging.
- ✓Use 2-space indentation for XML files stored in version control — it produces shorter lines and cleaner git diffs.
- ✓Use 4-space indentation when working with Java ecosystem files like Maven POM files or Spring XML configurations to match the conventional style.
- ✓Always escape special characters in XML text content: use `&` for `&`, `<` for `<`, `>` for `>`, `"` for `"`, and `'` for `'`.
- ✓After formatting, check that the indent level returns to 0 at the end of the document — if it doesn't, you have unclosed opening tags.
- ✓Use the minified output when embedding XML as a string in JavaScript, Java, or Python code to avoid multiline string complications.
- ✓For SOAP API debugging, format the raw request and response envelopes side-by-side to quickly spot differences in element names or attribute values.
- ✓Self-closing tags (`<element />`) are semantically equivalent to `<element></element>` and can reduce verbosity in configuration XML.
- ✓When editing Android layout XML, prefer 2-space indentation to keep deeply nested view hierarchies within a readable line width.
Frequently Asked Questions
Sources & References
Last updated: 2026-06-05
Help us improve!
How would you rate the XML Formatter?
Editorial Note
MyCalcBuddy Editorial Team
This page is maintained as an educational calculator reference.
Formula Source: Standard Mathematical References
by Various