Formatting of XML created by DataContractSerializer Formatting of XML created by DataContractSerializer xml xml

Formatting of XML created by DataContractSerializer


As bendewey says, XmlWriterSettings is what you need - e.g. something like

var ds = new DataContractSerializer(typeof(Foo));var settings = new XmlWriterSettings { Indent = true };using (var w = XmlWriter.Create("fooOutput.xml", settings))    ds.WriteObject(w, someFoos);


Take a look at the Indent property of the XmlWriterSettings

Update: Here is a good link from MSDN on How to: Specify the Output format on the XmlWriter

Additionally, here is a sample:

class Program{    static void Main(string[] args)    {        var Mark = new Person()        {            Name = "Mark",            Email = "mark@example.com"        };        var serializer = new DataContractSerializer(typeof(Person));        var settings = new XmlWriterSettings()        {            Indent = true,            IndentChars = "\t"        };        using (var writer = XmlWriter.Create(Console.Out, settings))        {            serializer.WriteObject(writer, Mark);        }        Console.ReadLine();    }}public class Person{    public string Name { get; set; }    public string Email { get; set; }}


Be careful about adjusting whitespace in XML documents! Adjusting whitespace will make the XML more readable for us humans, but it may interfere with machine parsing.

According to the XML standard, whitespace is significant by default. In other words, as far as XML is concerned, white space is content.

If you feed your nicely formatted XML into an XML Document object, you will get a different result than the version that has no spaces or line breaks in it. You will get additional text nodes added to the version that has been formatted.

This MSDN article on XML White Space has several examples that show how tricky white space can be.

If you're formatting the XML only for human consumption, it doesn't matter. But if you try to round-trip your formatted document, you could run into trouble.

Since one of the key primary benefits of using DataContractSerializer is the ability to serialize objects and deserialize XML seamlessly, it's usually best to leave the ugly output alone.

I usually paste the output into NotePad++ and run an XML-tidy macro over it when I want to read it for debugging purposes.