我正在反序列化以下由序列化生成的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读取文件时,它不返回任何内容。
答案 0 :(得分:1)
我已将Load
方法设为静态,并尝试了此方法...在这里工作正常。这是代码:
void Main()
{
new BattInfo(new BattModel(){ BattName= "test"}).Save(@"tmp.xml");
Console.Out.Write(BattInfo.Load(@"tmp.xml").Battery[0].BattName);
}
// Define other methods and classes here
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 static BattInfo Load(string filename)
{
XmlReader reader = XmlReader.Create(filename);
XmlSerializer serializer = new XmlSerializer(typeof(BattInfo));
return (BattInfo)serializer.Deserialize(reader);
}
}
您是否期望Load
方法填充您从中调用它的现有实例?简而言之,XmlSerializer
具有严格的构造性,因此您无法设计。