XML Formatter

Format and pretty-print XML with syntax highlighting

Try an example

XML Input

Formatted XML

Runs locally · Safe to paste secrets
Formatted XML will appear here…

What is XML Formatting?

XML formatting (also called XML pretty-printing or XML beautification) is the process of adding consistent indentation and line breaks to an XML document so that its hierarchical structure becomes visible. Raw XML from APIs, config generators, or serializers is often delivered as a single line with no whitespace between tags. An XML formatter parses that document into a tree, then re-serializes it with predictable spacing.

The XML 1.0 specification (W3C Recommendation, fifth edition) defines a strict grammar where every opening tag must have a matching closing tag or be self-closing, attributes must be quoted, and five characters (<, >, &, ", ') require entity escaping. A formatter must respect these rules while inserting only insignificant whitespace that does not alter the document's information set (infoset).

Formatted XML is easier to read during code review, easier to diff in version control, and easier to debug when a service returns unexpected data. The formatting operation itself is lossless: the logical content of the document stays identical, only the presentation changes. Tools like git diff and pull-request review platforms show only modified lines — consistently indented XML ensures those diffs reflect real changes, not reformatting noise.

Before · xml
After · xml
<catalog><book id="bk101"><author>Gambardella, Matthew</author><title>XML Developer's Guide</title><genre>Computer</genre><price>44.95</price><publish_date>2000-10-01</publish_date></book><book id="bk102"><author>Ralls, Kim</author><title>Midnight Rain</title><genre>Fantasy</genre><price>5.95</price><publish_date>2000-12-16</publish_date></book></catalog>
<catalog>
  <book id="bk101">
    <author>Gambardella, Matthew</author>
    <title>XML Developer's Guide</title>
    <genre>Computer</genre>
    <price>44.95</price>
    <publish_date>2000-10-01</publish_date>
  </book>
  <book id="bk102">
    <author>Ralls, Kim</author>
    <title>Midnight Rain</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2000-12-16</publish_date>
  </book>
</catalog>

Why Use an Online XML Formatter?

Formatting XML by hand is error-prone and slow, especially for documents with deep nesting or mixed namespaces. A browser-based formatter gives you a formatted result in under a second, regardless of file size.

Instant pretty-print
Paste or type XML and get indented output immediately. No waiting for a CLI tool to install or a build step to run.
🔒
Privacy-first processing
All parsing and formatting happens in your browser using the DOMParser API. Your XML never leaves your machine and is never sent to any server.
🎨
Configurable indentation
Choose between 2-space, 4-space, or tab indentation to match your project's coding standards without editing config files.
📋
No account or install required
Open the page, paste your XML, and copy the result. No sign-up forms, no desktop software, no browser extensions.

XML Formatter Use Cases

Frontend development
Inspect SVG markup or XHTML fragments returned by a CMS. Formatting the raw output lets you locate specific attributes and nested groups quickly.
Backend engineering
Debug SOAP responses, RSS feeds, or XML-RPC payloads from third-party services. Pretty-printed output lets you trace missing elements or incorrect namespaces.
DevOps and CI/CD
Read Maven pom.xml files, Ant build scripts, or .csproj project files that have been machine-generated with no indentation. Format them before committing to keep diffs clean.
QA and testing
Compare expected vs. actual XML payloads in integration tests. Formatting both sides to the same indentation style eliminates false negatives caused by whitespace differences.
Data engineering
Inspect XML exports from databases, ETL pipelines, or government open-data portals. Formatted XML reveals the record structure before you write an XSLT transform or XPath query.
Learning XML
Students working through W3C XML tutorials can paste exercise files into the formatter to verify that their nesting and attribute syntax is correct.

XML Predefined Entity Reference

XML reserves five characters for its syntax. When these characters appear as literal text content or attribute values, they must be replaced with predefined entity references. A correct formatter preserves these entities during pretty-printing.

CharacterRole in XMLEntity
<Start of tag&lt;
>End of tag&gt;
&Start of entity&amp;
"Attribute delimiter&quot;
'Attribute delimiter&apos;

XML Indentation Styles Compared

There is no single standard for XML indentation. The choice depends on your team's conventions and the tools in your pipeline. Here are the three most common styles.

2 spaces (recommended)
The most common choice for web-related XML: SVG, XHTML, SOAP, Spring config. Keeps deeply nested documents compact. Used by default in most online formatters and IDEs.
4 spaces
Preferred in Java ecosystems (Maven, Ant, Android manifests) where files rarely exceed 3-4 levels of nesting. Matches the default indentation of Java and C# code.
Tab character
Lets each developer set their own visual width in their editor. Common in legacy projects and some Microsoft tooling (.csproj, .nuspec). Produces smaller file sizes than spaces.

Code Examples: Format XML Programmatically

When you need to format XML inside a script or build process, every major language has a built-in or standard-library option. Below are working examples you can copy directly.

JavaScript (DOM API)
const raw = '<root><item>hello</item></root>'
const parser = new DOMParser()
const doc = parser.parseFromString(raw, 'application/xml')
const serializer = new XMLSerializer()
const xml = serializer.serializeToString(doc)

// Indent with XSLT (browser-native approach)
const xslt = new DOMParser().parseFromString(`
  <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="node()|@*">
      <xsl:copy><xsl:apply-templates select="node()|@*"/></xsl:copy>
    </xsl:template>
  </xsl:stylesheet>`, 'application/xml')

const proc = new XSLTProcessor()
proc.importStylesheet(xslt)
const formatted = proc.transformToDocument(doc)
console.log(new XMLSerializer().serializeToString(formatted))
// → <root>\n  <item>hello</item>\n</root>
Python
import xml.dom.minidom

raw = '<root><item>hello</item><item>world</item></root>'
dom = xml.dom.minidom.parseString(raw)
print(dom.toprettyxml(indent='  '))
# → <?xml version="1.0" ?>
# → <root>
# →   <item>hello</item>
# →   <item>world</item>
# → </root>

# With lxml (handles namespaces, XSD, large files)
from lxml import etree
tree = etree.fromstring(raw.encode())
print(etree.tostring(tree, pretty_print=True).decode())
Go
package main

import (
    "encoding/xml"
    "fmt"
    "strings"
)

func formatXML(raw string) (string, error) {
    decoder := xml.NewDecoder(strings.NewReader(raw))
    var out strings.Builder
    encoder := xml.NewEncoder(&out)
    encoder.Indent("", "  ")
    for {
        tok, err := decoder.Token()
        if err != nil {
            break
        }
        encoder.EncodeToken(tok)
    }
    encoder.Flush()
    return out.String(), nil
}
// formatXML("<a><b>1</b></a>") → "<a>\n  <b>1</b>\n</a>"
CLI (xmllint)
# Format XML file with xmllint (part of libxml2, pre-installed on macOS/Linux)
xmllint --format input.xml > formatted.xml

# Format from stdin
echo '<a><b>1</b></a>' | xmllint --format -
# → <?xml version="1.0"?>
# → <a>
# →   <b>1</b>
# → </a>

# Validate and format at the same time
xmllint --format --schema schema.xsd input.xml

Frequently Asked Questions

Does formatting XML change the document's meaning?
No. XML formatting only adds or removes insignificant whitespace between tags. The XML Information Set (infoset) stays identical. One exception: if your schema uses xml:space="preserve" on certain elements, a formatter should leave those elements untouched, and this tool respects that.
What is the difference between XML formatting and XML validation?
Formatting adds indentation and line breaks to make XML readable. Validation checks whether the document conforms to a schema (XSD, DTD, or RelaxNG). A document can be well-formed but invalid against its schema. Use this formatter for readability and the XML Validator tool for schema compliance.
Can I format XML with namespaces?
Yes. The browser's DOMParser handles XML namespaces natively. Namespace prefixes, default namespace declarations (xmlns), and qualified attribute names are all preserved during formatting. The formatter does not add, remove, or rename any namespace bindings.
How large of an XML file can I format in the browser?
Browser-based formatting works well for documents up to roughly 10 MB. Beyond that, the DOM tree consumes significant memory and the UI may become unresponsive. For very large files, use a CLI tool like xmllint --format, which processes XML as a stream.
Why does my formatted XML have an XML declaration added?
Some formatters prepend <?xml version="1.0"?> when serializing the DOM tree. This declaration is optional in XML 1.0 when the encoding is UTF-8. If you do not want it, remove the first line from the output. The declaration does not affect parsing by any conforming XML processor.
Is XML formatting the same as XML minification?
They are opposite operations. Formatting adds whitespace to improve readability. Minification removes all non-essential whitespace to reduce file size. Both operations are lossless with respect to the XML infoset. If you need to minify XML, use the XML Minifier tool.
What is the difference between XML and HTML formatting?
XML is strict: every tag must be closed, attribute values must be quoted, and the document must have exactly one root element. HTML (specifically HTML5) is lenient: optional closing tags, unquoted attributes, and void elements like &lt;br&gt; are all valid. An XML formatter will reject invalid XML, while an HTML formatter tolerates syntax that XML would not allow.