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