如何确保DataContractSerializer的文件输出是“常规”格式的XML?

时间:2011-09-20 16:30:56

标签: xml serialization

每次从DataContractSerializer输出XML时,它都是单行XML字符串。这是有效的XML,但阅读起来很痛苦。如何在其中添加额外的空格以将元素分解为标签线?

public void Save(Stream stream)
{
    DataContractSerializer serializer = new DataContractSerializer(typeof(ObservableCollection<PlottingDeviceInfo>));
    serializer.WriteObject(stream, this.Devices);
}

1 个答案:

答案 0 :(得分:5)

使用XmlWriter的{​​{3}}重载,然后将其XmlWriter传递给public void Save(Stream stream) { DataContractSerializer serializer = new DataContractSerializer(typeof(ObservableCollection<PlottingDeviceInfo>)); using (var writer = XmlWriter.Create(stream, new XmlWriterSettings{Indent=true})) { serializer.WriteObject(writer, this.Devices); } } 以产生漂亮的输出。

Stream

当您使用WriteObject时,XmlWriter会创建自己的默认XmlWriter。确定格式等的是{{1}}