我想使用 XmlSerializer 序列化多个对象。序列化操作运行正常,但是当我想反序列化对象时,反序列化只返回第一个对象,如果我再次调用它,它返回 null!
我希望我的序列化是自定义的,所以我实现了 IXmlSerializabe :
public class Person : IXmlSerializable
{
public int id;
public string name;
public virtual void WriteXml(XmlWriter writer)
{
Type type = this.GetType();
FieldInfo[] pInfo = type.GetFields();
foreach (FieldInfo property in pInfo)
{
object value = property.GetValue(this);
writer.WriteElementString(property.Name, value.ToString());
}
}
public virtual void ReadXml(XmlReader reader)
{
Type type = this.GetType();
FieldInfo[] pInfo = type.GetFields();
foreach (FieldInfo property in pInfo)
{
object value = null;
reader.ReadToFollowing(property.Name);
Type propertyType = property.FieldType;
value = reader.ReadElementContentAs(property.FieldType, null);
type.GetField(property.Name).SetValue(this, value);
}
reader.Read();
}
public virtual XmlSchema GetSchema()
{
return (null);
}
}
我这样称呼它:
// Serialize
Type type = typeof(Person);
XmlSerializer serializer = new XmlSerializer(type);
TextWriter writer = new StreamWriter(filename);
foreach (Person c in list)
{
serializer.Serialize(writer, c);
}
writer.Close();
// Deserialize
XmlReader reader = XmlReader.Create(filename);
var objectsList = serializer.Deserialize(reader);
序列化创建以下 xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<Person>
<id>1</id>
<name>name1</name>
</Person><?xml version="1.0" encoding="utf-8"?>
<Person>
<id>2</id>
<name>name2</name>
</Person>