.NET 6 XmlSerializer 漂亮的打印

.NET 6 XmlSerializer Pretty print

我有这个示例 .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>

要编写缩进 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

As @sveinungf wrote in the comment - using XmlWriter.Create is 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());