Serialize(TextWriter,Object)vs Serialize(XmlWriter,Object)

时间:2016-03-22 06:29:25

标签: c# xml serialization

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。

1 个答案:

答案 0 :(得分:1)

我在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并为您设置格式。