使用 XmlSerializer 将多个对象自定义序列化/反序列化为一个 xml 文件/从 xml 文件进行反序列化

本文关键字:xml 文件 反序列化 一个 XmlSerializer 序列化 自定义 使用 对象 | 更新日期: 2023-09-27 18:31:21

我想使用 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>

使用 XmlSerializer 将多个对象自定义序列化/反序列化为一个 xml 文件/从 xml 文件进行反序列化

我找到了答案。更正的代码:

    public virtual void ReadXml(XmlReader reader)
    {
        Type type = this.GetType();
        FieldInfo[] pInfo = type.GetFields();
        // Added
        reader.ReadStartElement();
        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);                
        }
        // Added
        reader.ReadEndElement();
    }
    // Serialize
    Type type = typeof(List<Person>); //Changed Type to List of Persons
    XmlSerializer serializer = new XmlSerializer(type);
    TextWriter writer = new StreamWriter(filename);
    serializer.Serialize(writer, list);
    writer.Close();