Skip to content
Owais Khan Software Reviews
How-To Guides

How to Format XML: A Guide to Indentation, Attributes, and Edge Cases

Learn how to format XML correctly. Master element indentation, attribute alignment, mixed content handling, and syntax validation rules.

By Owais Khan

Formatting XML involves arranging raw markup into a structured hierarchy using consistent line breaks and indentation levels—typically two, three, or four spaces—while correctly managing whitespace-sensitive elements, multi-line attributes, and tag closures. Standard tools reformat files either manually through editor commands or automatically when pasting content or closing tags.

Formatting issues rarely arise from standard nested tags. They occur when parsers encounter irregular data structures, such as mixed markup and freeform text, or bloated tag headers with dense attributes. Mastering these specific problem areas makes standard document formatting straightforward.

Handling Mixed Content Without Breaking Text Structure

An element contains mixed content when it includes both character data and child elements within the same tag boundary. Automated pretty-printing often breaks mixed content because general formatting logic attempts to insert line breaks and indentation around every tag, which introduces unintentional whitespace directly into human-readable text strings.

To control formatting behavior in these scenarios, XML provides the xml:space attribute, which accepts values such as preserve or default. Setting xml:space="preserve" tells an editor or formatting engine to leave the enclosed text, spaces, and line breaks untouched rather than applying automated indentation rules. Visual Studio, for instance, includes a setting to format mixed content by default, but it explicitly skips reformatting whenever content falls inside an xml:space="preserve" scope.

Consider a real-world scenario where a description contains inline formatting elements alongside continuous sentences:

<!-- Raw, unformatted mixed content -->
<productDescription xml:space="preserve">The gadget includes a <status active="true">certified</status> lithium-ion cell that charges in 30 minutes.</productDescription>

If a pretty-printer indents this without respecting whitespace preservation, it places <status active="true"> on a new line and indents the word certified. When an application parses that result, it may read unintended gaps before and after the status element. Using the xml:space="preserve" attribute ensures that the layout and exact character strings are parsed identically regardless of global formatting settings.

Managing Multi-Line Attribute Alignment and Auto-Formatting Triggers

Elements containing numerous attributes create extremely long, horizontal lines of text. Without clear line wrapping, reading and validating configuration files becomes difficult. Editors address this challenge with specific attribute alignment rules.

Under Visual Studio’s formatting options, the default behavior is to preserve manual attribute formatting. However, when attributes span multiple lines, the editor indents each subsequent line of attributes to match the indentation of the parent element. Alternatively, editors offer an option to align attributes each on a separate line. When enabled, this aligns the second and subsequent attributes vertically to match the indentation position of the first attribute.

Editors also support automated reformatting triggers. Instead of requiring you to execute a menu command every time you edit a document, you can configure environments to auto-reformat on paste from the clipboard or on completion of an end tag. Paired with automatic quotation insertion (which inserts ="" and places the cursor between the quotes) and automatic tag closure, the editor maintains consistent document layout as you type.

Here is a worked example demonstrating the transformation of an unformatted, single-line configuration into an aligned multi-line structure:

Input (Single-line unformatted source)

<serverDeployment env="staging" cluster="us-west-2" minReplicas="3" maxReplicas="12" autoScale="true"><serviceName>auth-gateway</serviceName><port protocol="https">8443</port></serverDeployment>

Formatted Output (Vertical attribute alignment and 2-space element indentation)

<serverDeployment env="staging"
 cluster="us-west-2"
 minReplicas="3"
 maxReplicas="12"
 autoScale="true">
 <serviceName>auth-gateway</serviceName>
 <port protocol="https">8443</port>
</serverDeployment>

In this output, child elements indent two spaces from the root level, and every attribute after the first aligns vertically beneath env="staging". This produces clean, readable code without altering how parsers interpret attribute key-value pairs.

Structuring Standard Documents and Running Syntax Validation

Once edge cases like mixed content and attribute spreading are resolved, the fundamental rules of XML pretty-printing become straightforward. XML is extensible, independent of any specific domain, and parsed into tokens according to strict grammatical rules. For standard data trees, a formatter establishes readability by:

  1. Placing each opening tag, closing tag, and distinct child node onto its own line.
  2. Indenting nested children relative to their parent element using an established width (such as 2, 3, or 4 spaces).
  3. Ensuring self-closing tags or leaf elements with single text nodes remain compact.

When writing documents manually or working across different operating systems like Windows, Mac, or Linux, desktop editors provide direct shortcut workflows. In Notepad++, users install the XML Tools plugin via the Plugins Admin menu. Once installed, selecting the Pretty print option under Plugins > XML Tools (or pressing CTRL + ALT + SHIFT + B) instantly reformats the entire active document.

Formatting requires correct underlying syntax. If a document has unclosed tags or syntax violations, a formatter cannot reliably determine tree depth or nesting levels. The XML Tools plugin in Notepad++ provides a “Check XML syntax now” command to pinpoint syntax errors. Similarly, dedicated tools act as an XML lint, displaying validation errors directly when malformed tags occur. If you need a fast way to clean up markup without installing desktop plugins or configuring IDE settings, you can paste your raw markup into our free XML Formatter to inspect tree hierarchies and indent code immediately.

Verification Test Inputs for XML Formatting Rules

To ensure your formatting engine or editor configuration functions accurately across all layout types, validate your setup against these three test inputs:

Test Case 1: Compact Nested Nodes with Sibling Elements

  • Input: <company><department name="Engineering"><team>DevOps</team><team>Security</team></department></company>
  • Expected Result: <company> starts on line 1; <department> indents on line 2; <team> elements indent further on lines 3 and 4; tags close in reverse order with matching indentation.

Test Case 2: Deeply Nested Attributes Requiring Alignment

  • Input: <database connectionTimeout="30" poolSize="100" retryAttempts="3" sslMode="verify-full"><host>db.internal.lan</host></database>
  • Expected Result: When attribute alignment is active, poolSize, retryAttempts, and sslMode stack on separate lines directly beneath connectionTimeout, while <host> begins on the subsequent line indented relative to <database>.

Test Case 3: Preserved Mixed Content Scope

  • Input: <notice xml:space="preserve">Order placed on <date>2026-03-30</date>. Please review your dashboard.</notice>
  • Expected Result: The formatter preserves inline text spacing surrounding the <date> tag rather than forcing <date> onto a new line, preventing whitespace corruption in the processed message.

Open the XML Formatter

Frequently asked questions

What indent sizes are standard for formatting XML?
Common XML indentation options support levels of 2 spaces, 3 spaces, or 4 spaces depending on personal or team formatting standards.
How can I format XML documents in Notepad++?
Install the XML Tools plugin through Plugins > Plugins Admin. Once installed, go to Plugins > XML Tools and select Pretty print, or use the keyboard shortcut CTRL + ALT + SHIFT + B.
What happens if I try to format an XML file that has missing closing tags?
A formatter cannot properly calculate indentation on malformed markup; you must check and fix syntax errors first using validation options like XML Tools' 'Check XML syntax now' or an XML lint tool.
How does Visual Studio handle multi-line attributes during formatting?
By default, Visual Studio preserves manual attribute formatting and indents multi-line attributes to match the parent element, but it can also be configured to align second and subsequent attributes vertically with the first attribute.
Can XML be formatted automatically as you type?
Yes, editors like Visual Studio can be set to automatically reformat XML on paste from the clipboard or upon the completion of an end tag.