每次从DataContractSerializer输出XML时,它都是单行XML字符串。这是有效的XML,但阅读起来很痛苦。如何在其中添加额外的空格以将元素分解为标签线?
public void Save(Stream stream)
{
DataContractSerializer serializer = new DataContractSerializer(typeof(ObservableCollection<PlottingDeviceInfo>));
serializer.WriteObject(stream, this.Devices);
}
答案 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}}