【发布时间】:2019-05-13 14:25:07
【问题描述】:
我正在反序列化以下由序列化生成的 xml。
<BattInfo>
<Battery>
<BattName>TestBattery</BattName>
<NumCellSeries>12</NumCellSeries>
<NumCellParallel>10</NumCellParallel>
<CelltoPackResistanceSum>3</CelltoPackResistanceSum>
<BattThermalResistance>15</BattThermalResistance>
<BattHeatCapacity>12</BattHeatCapacity>
</Battery>
</BattInfo>
我使用的代码是:
public class BattModel
{
public string BattName { get; set; }
public double NumCellSeries { get; set; }
public double NumCellParallel { get; set; }
public double CelltoPackResistanceSum { get; set; }
public double BattThermalResistance { get; set; }
public double BattHeatCapacity { get; set; }
}
public class BattInfo
{
[XmlElement("Battery")]
public List<BattModel> Battery { get; set; }
public BattInfo()
{
this.Battery = new List<BattModel>();
}
public BattInfo(params BattModel[] data) : this()
{
this.Battery.AddRange(data);
}
public void Save(string filename)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create(filename, settings);
XmlSerializer serializer = new XmlSerializer(typeof(BattInfo));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
serializer.Serialize(writer, this,ns);
writer.Flush();
writer.Close();
}
public BattInfo Load(string filename)
{
XmlReader reader = XmlReader.Create(filename);
XmlSerializer serializer = new XmlSerializer(typeof(BattInfo));
return (BattInfo)serializer.Deserialize(reader);
}
}
xml 被正确序列化。但是当我尝试从使用序列化生成的 xml 中读取它时,它在通过 xmlreader 读取文件时返回 none。
【问题讨论】:
-
代码与这个调用一起工作: BattInfo loadedData = batteryInfo.Load(FILENAME);您正在返回序列化数据,可能您想要 this = (BattInfo)serializer.Deserialize(reader);
-
@jdweng 问题是,当我使用断点时,我发现这个 Load 函数中没有填充阅读器。 reader 的值为 {None}。
-
@jdweng -
this = (BattInfo)serializer.Deserialize(reader);不正确...如果你尝试你应该得到:Cannot assign to '' because it is read-only 跨度> -
这也是我得到的。如果必须复制阅读器。阅读器从一开始就没有显示任何内容。 Deserialize() 方法返回数据。
-
对,你不能用这个。
标签: c# xml serialization xmlreader