.NET 6 XmlSerializer 漂亮的打印
Posted
技术标签:
【中文标题】.NET 6 XmlSerializer 漂亮的打印【英文标题】:.NET 6 XmlSerializer Pretty print 【发布时间】:2021-10-04 19:40:09 【问题描述】:我有这个示例 .NET 6 程序将序列化对象打印到 XML:
using System.Text;
using System.Xml.Serialization;
var serializer = new XmlSerializer(typeof(Order));
var order = new Order
Address = new Address
FirstName = "Name"
;
await using var memoryStream = new MemoryStream();
var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8);
serializer.Serialize(streamWriter, order);
var result = Encoding.UTF8.GetString(memoryStream.ToArray());
Console.WriteLine(result);
public class Order
public Address Address;
public class Address
public string FirstName;
这会导致以下输出:
<?xml version="1.0" encoding="utf-8"?><Order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Address><FirstName>Name</FirstName></Address></Order>
在 .NET 5 和 .NET Core 3 中,类似的代码会生成如下所示的漂亮打印 XML。如何在 .NET6 中格式化此 XML?
<?xml version="1.0" encoding="utf-8"?>
<Order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Address>
<FirstName>Name</FirstName>
</Address>
</Order>
【问题讨论】:
【参考方案1】:要编写缩进的 xml,您可以使用 XmlTextWriter
(而不仅仅是 StreamWriter
)将 Formatting
设置为 Formatting.Indented
:
await using var memoryStream = new MemoryStream();
XmlTextWriter streamWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
streamWriter.Formatting = Formatting.Indented;
serializer.Serialize(streamWriter, order);
var result = Encoding.UTF8.GetString(memoryStream.ToArray());
UPD
正如@sveinungf 在评论中所写 - 使用XmlWriter.Create
是recommended approach,所以代码可以看起来像这样(还要注意create 方法可以接受StringBuilder
和文件名也可以在某些情况下更方便场景):
await using var memoryStream = new MemoryStream();
var streamWriter = XmlWriter.Create(memoryStream, new()
Encoding = Encoding.UTF8,
Indent = true
);
serializer.Serialize(streamWriter, order);
var result = Encoding.UTF8.GetString(memoryStream.ToArray());
【讨论】:
请注意,XmlTextWriter
是 no longer recommended to use。现在建议改用XmlWriter.Create
。
@sveinungf 谢谢你,更新了!以上是关于.NET 6 XmlSerializer 漂亮的打印的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 .NET XmlSerializer 使值类型可以为空?
使用 XmlSerializer 将 XML 反序列化为类型
强制 ASMX 代理使用 XmlSerializer 而不是 DataContractSerializer