C# 如何格式化输出漂亮的xml字符串

推荐使用XDocument格式化XML,其ToString()方法默认支持缩进输出,代码简洁;若使用XmlDocument,则需配合XmlWriterSettings设置Indent和IndentChars以实现美化输出。

在 C# 中,要格式化输出漂亮的 XML 字符串(即带有缩进和换行的可读格式),可以使用 XmlDocumentXDocument 结合适当的保存选项。以下是几种常用方法:

使用 XmlDocument 格式化输出

通过 XmlDocument 加载或创建 XML,并设置 PreserveWhitespaceSave 方法配合 XmlWriter 来实现美化输出。

示例代码:

using System;
using System.IO;
using System.Xml;

var doc = new XmlDocument(); doc.LoadXml("北京");

var settings = new XmlWriterSettings { Indent = true, IndentChars = " ", // 使用两个空格缩进 Encoding = System.Text.Encoding.UTF8, NewLineChars = "\n" };

using (var writer = XmlWriter.Create(Console.Out, settings)) { doc.Save(writer); }

输出结果会自动换行并缩进,结构清晰。

使用 XDocument 格式化输出

XDocument 是 LINQ to XML 的一部分,更现代且简洁。只要不压缩保存,默认 ToString() 就支持格式化输出。

示例代码:

using System;
using System.Xml.Linq;

var doc = new XDocument( new XElement("root", new XElement("person", new XAttribute("name", "张三"), new XAttribute("age", "30"), new XElement("city", "北京") ) ) );

Console.WriteLine(doc.ToString()); // 自动格式化输出

XDocument.ToString() 默认使用缩进,输出美观,适合快速开发。

手动控制格式化字符串(如从字符串解析)

如果你有一个未格式化的 XML 字符串,想美化它,可以先用 XDocument.Parse 解析,再调用 ToString()

string xmlString = "";
var doc = XDocument.Parse(xmlString);
Console.WriteLine(doc.ToString());

这样就能把一行 XML 转为带缩进的多行格式。

基本上就这些。推荐优先使用 XDocument,语法简洁,格式化天然支持。如果必须用 XmlDocument,记得搭配 XmlWriterSettings 设置缩进参数。