如何在使用XmlSerializer时添加换行符

时间:2010-12-06 06:38:13

标签: c# .net xml xml-serialization

我想知道如何在使用XmlSerializer时为每个元素添加换行符?

示例代码:

XmlSerializer serializer = new XmlSerializer(typeof(xxx));
using (XmlWriter xmlWriter = XmlWriter.Create("test.xml")
{
    serializer.Serialize(xmlWriter, xxx);
}

2 个答案:

答案 0 :(得分:29)

创建XmlWriter时,传入XmlWriterSettings对象,Indent设置为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);
}

答案 1 :(得分:6)

您可以使用XmlWriterSettings并将属性设置为缩进和换行符。 .Indent和.NewLineOnAttributes似乎是你想要的。

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