Home > Software engineering >  .NET 6 XmlSerializer Pretty print
.NET 6 XmlSerializer Pretty print

Time:10-06

I've this sample .NET 6 program printing out a serialised object to 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;
}

This results in this output:

<?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>

In .NET 5 and .NET Core 3 similar code results in pretty printed XML like below. How can I format this XML in .NET6?

<?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>

CodePudding user response:

You can use XmlTextWriter (instead of just StreamWriter) with Formatting set to 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());
  • Related