Development Tools • Published August 30, 2026 • 20 min read

XML Formatter & Beautifier Guide: How to Pretty Print, Validate, and Structure XML Files Online

Format, beautify, and validate XML documents online. Discover the best XML formatter and beautifier tools to pretty print sitemaps, SOAP APIs, and config files.

XML Formatter & Beautifier Guide: How to Pretty Print, Validate, and Structure XML Files Online
Master XML formatting and validation. Learn how to pretty print XML, indent nested elements, troubleshoot parsing errors, and use free online XML beautifier tools.
Structured XML document with indented child nodes and attribute highlighting
Figure 1: Anatomy of a well-formed, pretty printed XML document with clear element hierarchies.

XML Formatter & Beautifier Guide: How to Pretty Print, Validate, and Structure XML Files Online

Extensible Markup Language (XML) has been a cornerstone of enterprise computing and data interchange for over two decades. Despite the widespread adoption of JSON in modern web development, XML remains heavily entrenched in enterprise software, powering everything from banking SOAP web services and enterprise message brokers (JMS, IBM MQ) to search engine XML sitemaps, Android application manifests, Maven configuration files, and SVG vector graphics.

However, XML documents returned by enterprise APIs or generated by automated build scripts often arrive minified into a single monolithic line. Because XML relies on verbose opening and closing tags, raw XML is notoriously difficult to read without proper formatting.

An XML formatter (also referred to as an XML beautifier, XML pretty printer, or XML viewer) is an essential utility that parses raw markup, validates syntax, and renders a clean, indented visual hierarchy.

In this comprehensive technical guide, we examine the rules of XML formatting, explore programmatic beautification across major programming languages, troubleshoot common parsing errors, and show you how to format XML online effortlessly.


1. Understanding XML Formatting: Minified vs. Beautified XML

To understand the value of an XML beautifier, compare a raw minified XML payload with its formatted equivalent.

Minified XML (Standard Machine Output):

<?xml version="1.0" encoding="UTF-8"?><order id="10098" status="shipped" timestamp="2026-08-30T08:00:00Z"><customer id="cust_554"><name>Eleanor Vance</name><email>eleanor@example.com</email><address type="shipping"><street>452 Industrial Parkway</street><city>Austin</city><state>TX</state><zip>78701</zip></address></customer><lineItems><item sku="SKU-8821" qty="2"><title>High-Performance SSD 2TB</title><price currency="USD">189.99</price></item><item sku="SKU-1044" qty="1"><title>USB-C Hub Multiport</title><price currency="USD">49.95</price></item></lineItems><summary subtotal="429.93" tax="35.47" total="465.40"/></order>

Beautified XML (Human-Readable Hierarchy):

<?xml version="1.0" encoding="UTF-8"?>
<order id="10098" status="shipped" timestamp="2026-08-30T08:00:00Z">
  <customer id="cust_554">
    <name>Eleanor Vance</name>
    <email>eleanor@example.com</email>
    <address type="shipping">
      <street>452 Industrial Parkway</street>
      <city>Austin</city>
      <state>TX</state>
      <zip>78701</zip>
    </address>
  </customer>
  <lineItems>
    <item sku="SKU-8821" qty="2">
      <title>High-Performance SSD 2TB</title>
      <price currency="USD">189.99</price>
    </item>
    <item sku="SKU-1044" qty="1">
      <title>USB-C Hub Multiport</title>
      <price currency="USD">49.95</price>
    </item>
  </lineItems>
  <summary subtotal="429.93" tax="35.47" total="465.40" />
</order>

By applying 2-space indentation and line breaks, the structural relationships between the root <order>, the <customer> profile, the <lineItems> array, and the self-closing <summary /> node become immediately clear.


2. Fundamental XML Syntax Rules: Well-Formed vs. Valid XML

When using an XML validator or formatter, it is vital to distinguish between two levels of compliance:

┌─────────────────────────────────────────────────────────────┐
│                       Valid XML                             │
│  Conforms to a specific Schema (XSD) or DTD Definition      │
│                                                             │
│   ┌─────────────────────────────────────────────────────┐   │
│   │                 Well-Formed XML                     │   │
│   │  Complies with basic W3C XML Syntax Specifications  │   │
│   │                                                     │   │
│   │   • Exactly one root element                        │   │
│   │   • All tags closed symmetrically                   │   │
│   │   • Proper nesting without overlapping tags         │   │
│   │   • All attribute values quoted ("value")           │   │
│   │   • Special characters escaped (&amp;, &lt;)        │   │
│   └─────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘

Rule 1: A Single Root Element

Every XML document must contain exactly one root element that wraps all other child nodes. Multiple top-level sibling tags are illegal.

Rule 2: Case Sensitivity

XML tags are strictly case-sensitive. <Product>, <product>, and <PRODUCT> represent three distinct elements. Opening with <Item> and closing with </item> is a fatal syntax violation.

Rule 3: Quoted Attribute Values

Unlike HTML5, where quotes around attribute values are optional in certain cases, XML strictly mandates quotes:

<!-- ❌ ILLEGAL XML (Attributes must be quoted) -->
<server port=8080 active=true />

<!-- ✅ VALID XML -->
<server port="8080" active="true" />

Rule 4: Self-Closing Tags

Empty elements must terminate with a forward slash: <br /> or <img src="logo.png" />.


3. Programmatic XML Pretty Printing Across Tech Stacks

Developers frequently need to format XML within automated backend pipelines and scripts. Here is how to pretty print XML across major programming environments:

1. JavaScript (Browser & Node.js)

In modern JavaScript, you can format XML using standard DOM parsing and formatting algorithms:

function formatXml(xmlString: string, indent: string = '  '): string {
  let formatted = '';
  let indentLevel = 0;
  
  // Normalize whitespace and split tags
  const tokens = xmlString.replace(/>s*</g, '><').split(/(?=[<])/);
  
  for (const token of tokens) {
    if (token.startsWith('</')) {
      // Closing tag: decrease indent level
      indentLevel = Math.max(0, indentLevel - 1);
      formatted += indent.repeat(indentLevel) + token + '
';
    } else if (token.startsWith('<?') || token.startsWith('<!')) {
      // Declaration or comment: maintain current indent
      formatted += indent.repeat(indentLevel) + token + '
';
    } else if (token.endsWith('/>')) {
      // Self-closing tag: keep current level
      formatted += indent.repeat(indentLevel) + token + '
';
    } else if (token.startsWith('<')) {
      // Opening tag: print and increase indent
      formatted += indent.repeat(indentLevel) + token + '
';
      // Only increase if not self-contained
      if (!token.includes('</')) {
        indentLevel++;
      }
    } else {
      formatted += indent.repeat(indentLevel) + token + '
';
    }
  }
  
  return formatted.trim();
}

2. Python (minidom & lxml)

Python provides robust built-in support for XML pretty printing:

import xml.dom.minidom

raw_xml = '<root><user id="101"><name>Sarah Connor</name><role>Admin</role></user></root>'

# Parse string into DOM object
dom = xml.dom.minidom.parseString(raw_xml)

# Pretty print with 4-space indentation
pretty_xml = dom.toprettyxml(indent="    ")
print(pretty_xml)

For high-performance production workloads handling large XML files, the lxml library is significantly faster:

from lxml import etree

root = etree.fromstring(raw_xml.encode('utf-8'))
pretty_xml = etree.tostring(root, pretty_print=True, encoding='unicode')
print(pretty_xml)

3. Command Line Interface (CLI)

When working on remote Linux servers, you can format XML files with xmllint:

# Pretty print an XML file to terminal
xmllint --format sitemap.xml

# Format and write directly to a new file
xmllint --format raw_response.xml --output formatted_response.xml

# Format directly from cURL
curl -s https://example.com/soap-api | xmllint --format -

4. XML Namespaces (xmlns) & XPath 3.0 Querying

In enterprise architectures, XML documents often merge elements from different vocabularies. Namespaces prevent naming collisions:

<root xmlns:h="http://www.w3.org/TR/html4/"
      xmlns:f="https://www.w3schools.com/furniture">
  <h:table>
    <h:tr><h:td>Apples</h:td><h:td>Bananas</h:td></h:tr>
  </h:table>
  <f:table>
    <f:name>African Oak Coffee Table</f:name>
    <f:width>80</f:width>
    <f:length>120</f:length>
  </f:table>
</root>

Extracting Data with XPath Expressions

XPath provides powerful declarative navigation through XML hierarchies:

  • //customer[@id='cust_554']/name: Selects the customer's name attribute or element.
  • //lineItems/item[price > 100]: Selects all expensive catalog items.
  • count(//item): Evaluates the total number of line items dynamically.

5. Transforming XML with XSLT Stylesheets

XSLT (Extensible Stylesheet Language Transformations) enables automated declarative transformations of XML documents into HTML web pages, JSON payloads, or alternative XML schemas:

<!-- Sample XSLT Transformation Template -->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <html>
      <body>
        <h2>Customer Order Summary</h2>
        <table border="1">
          <tr bgcolor="#f2f2f2">
            <th>Item SKU</th>
            <th>Title</th>
            <th>Price</th>
          </tr>
          <xsl:for-each select="order/lineItems/item">
            <tr>
              <td><xsl:value-of select="@sku"/></td>
              <td><xsl:value-of select="title"/></td>
              <td><xsl:value-of select="price"/></td>
            </tr>
          </xsl:for-each>
        </table>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

6. XML Schema Validation: DTD vs. XSD Schema Definitions

Validating XML against formal contracts ensures enterprise integrations do not fail at runtime due to missing tags or corrupt types:

XML Schema Definition (XSD) Example:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="order">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="customer">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="name" type="xs:string"/>
              <xs:element name="email" type="xs:string"/>
            </xs:sequence>
            <xs:attribute name="id" type="xs:string" use="required"/>
          </xs:complexType>
        </xs:element>
        <xs:element name="total" type="xs:decimal"/>
      </xs:sequence>
      <xs:attribute name="id" type="xs:integer" use="required"/>
    </xs:complexType>
  </xs:element>
</xs:schema>

Using XSD schemas allows strict compile-time verification of banking transfers, invoices, and insurance claims.


7. Troubleshooting Common XML Formatting and Parsing Errors

When an XML formatter online reports a syntax error, it is usually caused by one of the following common pitfalls:

Issue 1: Unescaped Reserved Characters

The characters & and < cannot appear unescaped inside XML text nodes.

<!-- ❌ ILLEGAL XML (Triggers "EntityRef: expecting ';'") -->
<message>Welcome to AT&T & Best Buy <online></message>

<!-- ✅ VALID XML (Using Entity References) -->
<message>Welcome to AT&amp;T &amp; Best Buy &lt;online&gt;</message>

<!-- ✅ VALID XML (Using CDATA Block) -->
<message><![CDATA[ Welcome to AT&T & Best Buy <online> ]]></message>

Issue 2: CDATA Block Corruptions

A CDATA (Character Data) block instructs the XML parser to treat everything inside it as raw text rather than markup. However, the sequence ]]> cannot appear inside a CDATA block because it terminates the block prematurely.

Issue 3: Namespace Prefix Missing

When using XML Namespaces (such as SOAP envelopes or SVG elements), tags with prefixes (e.g., <soap:Envelope>) must have their namespace declared on the element or an ancestor node using the xmlns attribute:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <m:GetStockPrice xmlns:m="http://example.com/stock">
      <m:StockSymbol>GOOGL</m:StockSymbol>
    </m:GetStockPrice>
  </soap:Body>
</soap:Envelope>

8. XML vs. JSON: Choosing the Right Format

While modern microservices gravitate toward JSON, understanding when to use each format is crucial for software architects:

| Feature / Criteria | XML (Extensible Markup Language) | JSON (JavaScript Object Notation) |

| :--- | :--- | :--- |

| Data Types | Text-only (types defined via XSD Schema) | Native types (String, Number, Boolean, Array, Null) |

| Attributes Support | Native element attributes (<node id="1">) | No native attributes (requires explicit properties) |

| Schema Validation | Mature, powerful (XSD, DTD, Schematron) | JSON Schema (Draft 7 / 2020-12) |

| Document Metadata | Excellent (Namespaces, Comments, CDATA) | Minimal (Comments unsupported in strict JSON) |

| Parsing Performance | Moderate (DOM/SAX parsing overhead) | Very High (Native V8 JSON.parse) |

| Primary Use Cases | Enterprise SOAP, Sitemaps, Android, SVG, Maven | REST APIs, GraphQL, NoSQL, Mobile Apps |


9. XML Security: Preventing XXE and XML Entity Expansion Attacks

When building backend services that parse user-supplied XML documents, security vulnerabilities can arise if the parser is improperly configured:

1. XML External Entity (XXE) Injection

If an XML parser resolves external entity declarations, an attacker can craft a payload referencing local server files (e.g., file:///etc/passwd) or trigger internal Server-Side Request Forgery (SSRF).

<!-- Malicious XXE Attack Payload -->
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
  <!ELEMENT foo ANY >
  <!ENTITY xxe SYSTEM "file:///etc/passwd" >]>
<foo>&xxe;</foo>

Mitigation: Disable DTDs (DOCTYPE) and external entity resolution completely in your XML parser configuration.

2. Billion Laughs Attack (XML Entity Expansion Bomb)

An exponential entity expansion attack where small nested entity references expand to gigabytes of data in memory, crashing the host server via Denial of Service (DoS).

Mitigation: Use modern parsers with strict entity expansion thresholds or utilize client-side tools like the DevToolAdda <a href="/tool/html-formatter">HTML & XML Formatter</a> which process data safely in the browser sandbox.


10. How to Format XML Online Using DevToolAdda

You can format, validate, and clean your XML files in seconds using our free online tool:

  1. Open the HTML & XML Formatter on DevToolAdda.
  2. Paste your raw XML string or upload your .xml document.
  3. Choose your desired indentation (2 spaces, 4 spaces, or tabs).
  4. Click Format to parse the markup, catch syntax violations, and generate the beautified output.
  5. Copy the formatted XML or download the file with one click.

11. Related Markup and Formatting Tools on DevToolAdda

  • HTML Formatter & Beautifier: Clean and indent HTML and XML files with real-time validation.
  • JSON Formatter: Format and pretty print JSON payloads.
  • SQL Formatter: Beautify complex SQL queries and database migrations.
  • CSS Formatter: Organize and structure CSS stylesheets.
  • Diff Checker: Compare two versions of XML or JSON files side-by-side to highlight additions, deletions, and modifications.

Explore all developer utilities across our Developer Tools Directory and Categories to boost your engineering productivity!

Developer validating XML schema against XSD specifications in a code editor
Figure 2: Real-time XML validation catching unclosed tags and invalid entity references.

Frequently Asked Questions

Q1. What is an XML formatter and what does it do?

An XML formatter (also called an XML beautifier or XML pretty printer) is a developer utility that takes raw, minified, or poorly indented XML text and organizes it into a structured, readable hierarchy. It applies consistent indentation (spaces or tabs), breaks nested tags onto individual lines, aligns XML attributes, and validates that all elements conform to XML syntax standards.

Q2. What is the difference between well-formed XML and valid XML?

A "well-formed" XML document complies with the fundamental syntax rules of XML: it has a single root element, all opening tags have matching closing tags, tags are properly nested without overlap, and attribute values are enclosed in quotes. A "valid" XML document is not only well-formed but also conforms strictly to a defined schema (such as an XSD or DTD schema definition) that dictates element names, data types, and allowed hierarchies.

Q3. Why does XML still matter when JSON is so popular?

While JSON is the preferred format for modern web and mobile APIs, XML remains dominant across enterprise systems. XML powers SOAP web services, Android UI layout manifests (AndroidManifest.xml), Apache Maven build files (pom.xml), SVG vector graphics, Microsoft Office OpenXML documents (.docx, .xlsx), RSS/Atom feeds, and search engine XML Sitemaps (sitemap.xml).

Q4. How do I handle special characters like ampersands and angle brackets in XML?

In XML, five characters are reserved and must be represented using predefined entity references: & as &amp;, < as &lt;, > as &gt;, " as &quot;, and ' as &apos;. Alternatively, large blocks of text containing special characters can be wrapped inside a CDATA block: <![CDATA[ <raw text with special & characters> ]]>.

Q5. How can I pretty print XML directly from the command line?

On Linux and macOS, you can format XML using the native xmllint tool: xmllint --format input.xml --output output.xml or using Python: cat input.xml | python3 -c "import sys, xml.dom.minidom as m; print(m.parseString(sys.stdin.read()).toprettyxml(indent=' '))".

Format and Clean Your Markup Today

Pretty print, indent, and validate HTML and XML files instantly with our free, client-side developer utilities.

Open Free HTML/XML Formatter