在 C# 中,要格式化输出漂亮的 XML 字符串(即带有缩进和换行的可读格式),可以使用 XmlDocument 或 XDocument 结合适当的保存选项。以下是几种常用方法:
使用 XmlDocument 格式化输出
通过 XmlDocument 加载或创建 XML,并设置 PreserveWhitespace 和 Save 方法配合 XmlWriter 来实现美化输出。
示例代码:
using System;
using System.IO;
using System.Xml;
<p>var doc = new XmlDocument();
doc.LoadXml("<root><person name=\"张三\" age=\"30\"><city>北京</city></person></root>");</p><p>var settings = new XmlWriterSettings
{
Indent = true,
IndentChars = " ", // 使用两个空格缩进
Encoding = System.Text.Encoding.UTF8,
NewLineChars = "\n"
};</p><p>using (var writer = XmlWriter.Create(Console.Out, settings))
{
doc.Save(writer);
}</p>输出结果会自动换行并缩进,结构清晰。
使用 XDocument 格式化输出
XDocument 是 LINQ to XML 的一部分,更现代且简洁。只要不压缩保存,默认 ToString() 就支持格式化输出。
示例代码:
using System;
using System.Xml.Linq;
<p>var doc = new XDocument(
new XElement("root",
new XElement("person",
new XAttribute("name", "张三"),
new XAttribute("age", "30"),
new XElement("city", "北京")
)
)
);</p><p>Console.WriteLine(doc.ToString()); // 自动格式化输出</p>XDocument.ToString() 默认使用缩进,输出美观,适合快速开发。
手动控制格式化字符串(如从字符串解析)
如果你有一个未格式化的 XML 字符串,想美化它,可以先用 XDocument.Parse 解析,再调用 ToString()。
string xmlString = "<root><item id=\"1\"/><item id=\"2\"/></root>"; var doc = XDocument.Parse(xmlString); Console.WriteLine(doc.ToString());
这样就能把一行 XML 转为带缩进的多行格式。
基本上就这些。推荐优先使用 XDocument,语法简洁,格式化天然支持。如果必须用 XmlDocument,记得搭配 XmlWriterSettings 设置缩进参数。
