XmlSerializer.Serialize Method具有接受TextWriter
和XmlWriter
的重载。
我的问题是以下示例中这两个重载之间的实际区别是什么? (list
是List<MyObjectModel>
)
示例1(带有TextWriter
):
XmlSerializer serializer = new XmlSerializer(typeof(MyObjectModel));
using (TextWriter writer = new StreamWriter(savePath))
{
serializer.Serialize(writer, list);
}
示例2(带有
XmlWriter
):XmlSerializer serializer = new XmlSerializer(typeof(MyObjectModel));
using (XmlWriter writer = XmlWriter.Create(savePath))
{
serializer.Serialize(writer, list);
}
到目前为止,我已经注意到:
1)
TextWriter
似乎会自动为您执行缩进。2)两者的默认编码均为UTF-8。
最佳答案
我发现the source code reference中的区别:
public void Serialize(TextWriter textWriter, object o, XmlSerializerNamespaces namespaces) {
XmlTextWriter xmlWriter = new XmlTextWriter(textWriter);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.Indentation = 2;
Serialize(xmlWriter, o, namespaces);
}
简而言之,
TextWriter
重载在引擎盖下使用XmlTextWriter
并为您设置格式。