XmlSerializer.Serialize Method具有接受TextWriterXmlWriter的重载。

我的问题是以下示例中这两个重载之间的实际区别是什么? (listList<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并为您设置格式。

10-08 17:44