C# Xml Serializing List<T> descendant with Xml Attribute

时光毁灭记忆、已成空白 提交于 2019-11-28 10:57:18

I went ahead and solved the problem by implementing IXmlSerializable. If a simpler solution exists, post it!

    [XmlRoot(ElementName="People")]
public class PersonCollection : List<Person>, IXmlSerializable
{
    //IT WORKS NOW!!! Too bad we have to implement IXmlSerializable
    [XmlAttribute]
    public string FavoritePerson { get; set; }

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }
    public void ReadXml(XmlReader reader)
    {
        FavoritePerson = reader[0];            
        while (reader.Read())
        {
            if (reader.Name == "Person")
            {
                var p = new Person();
                p.FirstName = reader[0];
                p.Age = int.Parse( reader[1] ); 
                Add(p);
            }
        }
    }
    public void WriteXml(XmlWriter writer)
    {
        writer.WriteAttributeString("FavoritePerson", FavoritePerson);
        foreach (var p in this)
        {
            writer.WriteStartElement("Person");
            writer.WriteAttributeString("FirstName", p.FirstName);
            writer.WriteAttributeString("Age", p.Age.ToString());
            writer.WriteEndElement();            
        }
    }
}

This isn't an answer to the question, but I thought I'd make a suggestion to ease in code development.

Add a new Add method to the PersonCollection class as such:

public class PersonCollection : List<Person>, IXmlSerializable
{
...
    public void Add(string firstName, int age)
    {
        this.Add(new Person(firstName, age));
    }
...
}

Then, by doing this, you can simplify your collection initializer syntax to:

var people = new PersonCollection
{
    { "Sue", 17 },
    { "Joe", 21 }
};
people.FavoritePerson = "Sue";

If you don't mind having to wrap all of the list functions, then you can embed the list as a property of the class rather than deriving from it.

You'd then use the XmlElement attribute to force the xml elements to be written out as a flat list (rather than being nested).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!