跳到主要内容
uencoder

如何Format 和 Beautify XML

Transform compact XML 为 readable, indented 格式化具有 proper nesting.

问题

你的 XML 是 minified 或 inconsistently indented, making 它困难到 读取和 调试.

前置条件

  • Understanding 的 XML 结构
  • 熟悉树-based markup

步骤

  1. 1. Validate the XML

    Before formatting, ensure the XML is well-formed: all tags are closed, attributes are quoted, and there is a single root element. Malformed XML cannot be reliably formatted.

    输入
    <root><item>text</item></root>
    输出
    well-formed
  2. 2. Apply indentation and line breaks

    Add a newline after each element and indent child elements relative to their parent. Use a consistent indent size (2 or 4 spaces). Self-closing tags and text content should be handled appropriately.

    输入
    <root><item>text</item></root>
    输出
    <root>\n  <item>text</item>\n</root>
  3. 3. Preserve significant whitespace

    XML has both significant and insignificant whitespace. Elements with xml:space="preserve" or mixed content must keep their whitespace. A good formatter respects these rules and does not alter significant whitespace.

    输入
    formatted XML
    输出
    readable, whitespace preserved

预期结果

well-formed, consistently indented XML document 该是 容易到 读取和 edit.

常见错误

Formatting breaks mixed content
Mixed content (text interspersed with elements, as in XHTML) has significant whitespace. Use a formatter that preserves mixed content whitespace.
Output is not well-formed
The input XML had errors. Fix the source XML before formatting.

排障指引

  • If the formatter changes the meaning of the document, check whether it normalized whitespace in a preserve context.
  • Use an XML validator first if the formatter fails.

安全限制

  • Formatting does not execute XML. However, parsing XML with DTD enabled can trigger XXE attacks. Use a safe parser.

相关工具

参考链接