23

I am wondering how to add a line break for each element when using XmlSerializer?

Sample code:

XmlSerializer serializer = new XmlSerializer(typeof(xxx));
using (XmlWriter xmlWriter = XmlWriter.Create("test.xml")
{
    serializer.Serialize(xmlWriter, xxx);
}
2
  • Why? A computer does not care about line breaks. Commented Dec 6, 2010 at 6:39
  • 13
    @leppie: However, a human might. That's the only reason for using XML anyways - otherwise you could just use binary data. Commented Dec 6, 2010 at 6:40

2 Answers 2

41

When creating the XmlWriter, pass in an XmlWriterSettings object with Indent set to true.

var xmlWriterSettings = new XmlWriterSettings() { Indent = true };
XmlSerializer serializer = new XmlSerializer(typeof(xxx));
using (XmlWriter xmlWriter = XmlWriter.Create("test.xml", xmlWriterSettings)
{
    serializer.Serialize(xmlWriter, xxx);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Or if using XmlTextWriter, set "obj.Formatting = Formatting.Indented" after construction
6

You can use XmlWriterSettings and set the properties to out the indentation and newlines. .Indent and .NewLineOnAttributes seem to be what you would want.

http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.