【发布时间】:2018-11-28 07:53:30
【问题描述】:
我有这样的课:
public class Response
{
public String AdditionalData = "";
public Boolean Success = false;
public int ErrorCode = 0;
public int WarningCode = 0;
public Transaction TransactionInfo = null;
public PosInfo PosInformation = null;
}
我可以成功地序列化它。但是当我将该类序列化 2 次并将其保存在 XML 文件中时,XML 编辑器中出现多根错误。我知道它需要一个 XML 元素作为根元素来围绕其他标签,但我不知道如何在序列化代码中添加根元素。 消毒器类如下:
public class Serializer
{
public void XMLSerializer(Response response)
{
string path = "D:/Serialization.xml";
FileStream fs;
XmlSerializer xs = new XmlSerializer(typeof(Response));
if(!File.Exists(path))
{
fs = new FileStream(path, FileMode.OpenOrCreate);
}
else
{
fs = new FileStream(path, FileMode.Append);
}
StreamWriter sw = new StreamWriter(fs);
XmlTextWriter xw = new XmlTextWriter(sw);
xw.Formatting = System.Xml.Formatting.Indented;
xs.Serialize(xw, response);
xw.Flush();
fs.Close();
}
}
【问题讨论】:
-
如果你需要序列化多个Response实例,你可以把所有的Response-objects放到一个列表中,然后序列化这个列表。
-
文件模式
append看起来可能是罪魁祸首... -
xml 规范说明了何时和数组出现在根级别的 Xml 中的“格式不正确”。这并不一定意味着它是错误的。许多日志文件都是 xml 格式,只是简单地将新的日志条目附加到日志文件的末尾,并以格式不正确的 xml 结尾。要在网络库中读取这些文件,您可以使用 XmlReader 并使用设置:settings.ConformanceLevel = ConformanceLevel.Fragment
-
如果您有一个文件顺序附加了多个 XML 文档,您可以使用
ReadObjects<T>从 this answer 到 Read nodes of a xml file in C# 将它们全部读入一个列表中。
标签: c# xml xmlserializer