views:

1909

answers:

5

This isn't a big deal for me, but is there an easy way to get DataContractSerializer to spit out formatted XML rather then one long string? I don't want to change the tags or content in anyway just have it add line breaks and tabs to make the XML more readable?

<tagA>
   <tagB>This is</tagB>   
   <tagC>Much</tagC>
   <tagD>
      <tagE>easier to read</tagE>
   </tagD>
</tagA>


<tagA><tagB>This is</tagB><tagC>Much</tagC><tagD><tagE>harder to read</tagE></tagD></tagA>
+5  A: 

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 = "[email protected]"
        };

        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; }
}
bendewey
A: 

Who do you expect to be reading this XML? It's meant for the program on the other end, not for humans!

If you want the XML to be pretty-printed, just copy and paste it into Visual Studio as an XML file. Then use CTRL-K CTRL-D (Format Document).

John Saunders
Mostly so I can open it and get an idea of how DataContractSerializer is interpreting my object graph. I like to get an idea of what is going on.
Eric Anastas
Then why not do what I suggested, and open it in an editor that understands XML, like the one built-in to Visual Studio (especially the 2008 version)?
John Saunders
I use this pretty-printing in my code when saving user settings to disk. The settings class is a DataContract, and doesn't have too many fields. In such a case, it's nice to make it human readable for support purposes such as manual editing.
Drew Noakes
I'd recommend that manual edits to XML be done with an XML editor, in order to prevent errors. In that case, again, formatting is not required.
John Saunders
+12  A: 

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);
Steve Willcock
A: 
    public static string SerializeEntity<T>(T source)
    {
        using (MemoryStream ms = new MemoryStream())
        {

                NetDataContractSerializer serializer = new NetDataContractSerializer();
                serializer.Serialize(ms, source);
                return System.Text.Encoding.ASCII.GetString(ms.ToArray());

        }
    }

    public static T DeSerializeEntity<T>(string xml)
    {
        using (MemoryStream ms = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(xml)))
        {
                NetDataContractSerializer serializer = new NetDataContractSerializer();
                return (T)serializer.Deserialize(ms);
        }
    }
Amit Bagga
Shouldn't that be UTF8, not ASCII?
Jonathan Allen
A: 

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.

dthrasher