我想知道如何在使用XmlSerializer时为每个元素添加换行符?
示例代码:
XmlSerializer serializer = new XmlSerializer(typeof(xxx));
using (XmlWriter xmlWriter = XmlWriter.Create("test.xml")
{
serializer.Serialize(xmlWriter, xxx);
}
答案 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