Formateur XML

Formatez et embellissez les documents XML avec structure plus propre pour les intégrations

What is XML Formatting?

XML formatting (also called pretty-printing or beautification) transforms compact or inconsistently indented XML into a consistently structured, human-readable representation. Unlike validation — which checks whether a document conforms to XML grammar rules — formatting focuses exclusively on visual presentation: adjusting indentation levels, adding line breaks between elements, aligning attributes, and normalizing whitespace patterns. The formatting process preserves the document's information set (infoset) intact — element names, attribute values, text content, namespace declarations, processing instructions, and CDATA sections all remain semantically identical. Only insignificant whitespace between elements changes. This makes XML formatting a safe, reversible operation that improves readability for configuration files, API responses, build scripts, and data interchange documents without altering their meaning or behavior.

XML Document Structure and Formatting Targets

Understanding XML's structural components is essential for effective formatting. Each component type requires different formatting decisions, and a good formatter handles all of them consistently:

Elements and nesting depth: Elements are the primary structural unit of XML. Formatting assigns indentation proportional to nesting depth — a child element is indented one level deeper than its parent. This visual hierarchy makes it immediately apparent which elements are siblings, which are children, and where each subtree begins and ends. For deeply nested documents (common in SOAP envelopes, Maven POM files, and Spring configuration), consistent indentation transforms an unreadable wall of angle brackets into a navigable tree structure.

Attributes: Elements may contain multiple attributes, and formatting decisions include whether to keep all attributes on the opening tag's line or break them across multiple lines. Short attribute lists (one or two attributes with short values) typically stay inline, while elements with many attributes or long attribute values benefit from one-attribute-per-line formatting with alignment to the element name. The XML specification treats attribute order as insignificant, so formatters may optionally sort attributes alphabetically for consistency.

Namespaces: Namespace declarations (xmlns and xmlns:prefix) are syntactically attributes, but they carry structural meaning. Formatters should preserve namespace declarations on their declaring element and ensure that the visual formatting does not obscure the scope of namespace bindings. In documents with multiple namespace prefixes (common in WSDL, XSLT, and SVG), clear formatting helps developers trace which prefix applies to which vocabulary.

Text content and mixed content: Elements containing only text (<name>John</name>) are typically left on a single line, while elements containing child elements are expanded with indentation. Mixed content — elements containing both text and child elements — presents a challenge because adding indentation whitespace would alter the text content. Quality formatters detect mixed content and preserve its original spacing.

Indentation Rules and Formatting Conventions

XML formatting conventions vary across ecosystems, but several widely adopted rules produce readable output across all XML-based formats. This tool applies industry-standard conventions that balance readability with reasonable line lengths:

Indent size: The most common indent sizes are 2 spaces and 4 spaces. Two-space indentation is preferred for deeply nested documents (Maven POM, Android layouts, SOAP messages) because it prevents excessive horizontal scrolling. Four-space indentation provides clearer visual separation for shallow documents. Tab characters are technically valid but create inconsistent rendering across editors and diff tools, so spaces are the dominant convention in XML ecosystems. This tool defaults to 2-space indentation, matching the conventions used by most XML editors and IDE formatters including IntelliJ IDEA, Eclipse, and VS Code's XML extension.

Line breaks: Each opening tag of an element-only container starts on a new line, indented to its nesting level. The closing tag aligns vertically with its corresponding opening tag. Self-closing elements (<element/>) occupy a single line at the appropriate indent level. Empty elements may use either the self-closing form or the expanded <element></element> form — this tool normalizes to self-closing syntax for conciseness.

Attribute formatting: When an element's opening tag exceeds a configurable line length (typically 80–120 characters), attributes break to the next line with alignment. The first attribute may stay on the tag line or drop to the next line. Multi-line attribute formatting is particularly valuable for elements with long namespace URIs, data attributes, or configuration properties where each attribute represents a distinct setting.

XML declaration and processing instructions: The XML declaration (<?xml version="1.0" encoding="UTF-8"?>) always appears on the first line with no preceding whitespace. Other processing instructions (<?xml-stylesheet ...?>) are placed on their own line with no indentation, as they exist outside the element hierarchy. The formatter preserves these exactly as authored, only ensuring proper line separation from the document content.

Comment formatting: Single-line comments remain inline. Multi-line comments are indented to the level of the surrounding elements, with the content indented one additional level inside the comment delimiters. This preserves the visual hierarchy while keeping comments clearly associated with their relevant section of the document.

Pretty-Printing Strategies for Different XML Use Cases

Different XML formats have distinct formatting needs based on their purpose, audience, and typical document depth. Effective formatting adapts to these contexts:

Configuration files (Maven POM, Spring XML, web.xml): These documents are read and edited by developers frequently. Consistent 2-space indentation with all elements expanded makes it easy to locate specific configuration sections, compare settings between environments, and produce clean diffs in version control. Configuration XMLs benefit from preserving blank lines between logical sections (dependencies, plugins, profiles) to improve scanability.

API responses (SOAP, REST XML): API responses are typically viewed for debugging purposes. Pretty-printing transforms a single-line response into a readable tree where response codes, error messages, and data payloads are immediately identifiable. For large responses (order lists, catalog feeds), formatting with collapsed long text nodes helps focus on the document structure rather than voluminous content.

Data interchange (EDI-XML, HL7, UBL invoices): Industry-standard XML formats often have deeply nested structures with repetitive element patterns. Formatting these documents with minimal indentation (2 spaces) and collapsed empty elements keeps file sizes manageable while still exposing the hierarchical structure. Line-wrapping long text values inside elements further improves readability without altering the parsed content.

Markup documents (XHTML, DocBook, DITA): Documents mixing structural elements with inline text content require mixed-content-aware formatting. A naive formatter that adds indentation inside paragraphs would introduce visible whitespace in rendered output. Intelligent formatters detect mixed-content elements and leave their internal whitespace untouched while still indenting the surrounding block-level structure.

Handling Special XML Content During Formatting

Several XML constructs require careful handling during formatting to avoid altering document semantics or breaking downstream parsers:

CDATA sections: CDATA sections (<![CDATA[...]]>) contain literal text that is not parsed for markup. A formatter must never modify whitespace inside CDATA content, as it may contain code snippets, pre-formatted text, or data where every character is significant. The CDATA delimiters themselves are placed at the appropriate indent level, but the enclosed content is preserved byte-for-byte. This is especially important for XML documents embedding JavaScript, SQL queries, or template code inside CDATA blocks.

Processing instructions: Processing instructions (<?target data?>) provide instructions to the application processing the XML. Common examples include <?xml-stylesheet?> for CSS/XSLT associations and application-specific instructions. Formatters should place each processing instruction on its own line without modifying its content, as the data portion has application-defined syntax that the formatter cannot safely restructure.

Whitespace-significant elements: Some elements declare xml:space="preserve" to indicate that all whitespace within them is meaningful. A conforming formatter must respect this attribute and skip indentation adjustments for the entire subtree of such elements. Common examples include <pre> elements in XHTML, <programlisting> in DocBook, and custom elements in domain-specific vocabularies that contain formatted text or code samples.

Entity references: Predefined entity references (&lt;, &gt;, &amp;, &quot;, &apos;) and custom entity references must pass through formatting unchanged. A formatter that expands entities would alter the document's physical representation and could break round-trip editing workflows. Numeric character references (&#x20AC; for €) are similarly preserved without expansion.

Code Examples

XML pretty-printing: before and after formatting

<!-- Before: compact single-line XML (hard to read) -->
<?xml version="1.0" encoding="UTF-8"?><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><description>An in-depth look at creating applications with XML.</description></book><book id="bk102"><author>Ralls, Kim</author><title>Midnight Rain</title><genre>Fantasy</genre><price>5.95</price></book></catalog>

<!-- After: formatted with 2-space indentation -->
<?xml version="1.0" encoding="UTF-8"?>
<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>
    <description>An in-depth look at creating applications with XML.</description>
  </book>
  <book id="bk102">
    <author>Ralls, Kim</author>
    <title>Midnight Rain</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
  </book>
</catalog>

Standards & Specifications

Questions Fréquentes

What is XML formatting?

XML formatting adds proper indentation and line breaks to XML documents, making them human-readable. It organizes nested elements with consistent spacing while preserving the document structure and data.

Does formatting validate my XML?

Yes, the formatter will detect syntax errors like unclosed tags, mismatched elements, or invalid characters. If your XML has errors, the tool will show you what's wrong so you can fix it.

Will formatting change my XML data?

No, formatting only changes whitespace between elements. The actual content, attributes, and structure remain unchanged. Your XML will parse and process exactly the same way after formatting.

Is my data sent to a server?

No, all XML formatting happens in your browser. Your data never leaves your device. This ensures complete privacy and security for sensitive information.