0

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

1 回答 1

2

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

    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();
于 2013-09-14T13:21:38.493 回答