Obsolete attribute causes property to be ignored by XmlSerialization

前端 未结 6 1091
臣服心动
臣服心动 2020-12-05 12:54

I\'m refactoring some objects that are serialized to XML but need to keep a few properties for backwards compatibility, I\'ve got a method that converts the old object into

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 13:31

    Another workaround is to subscribe to XmlSerializer.UnknownElement, when creating the serializer for the datatype, and then fix old data that way.

    http://weblogs.asp.net/psteele/archive/2011/01/31/xml-serialization-and-the-obsolete-attribute.aspx

    Maybe consider to have the method for subscribing as a static method on the class for datatype.

    static void serializer_UnknownElement(object sender, XmlElementEventArgs e)
    {
        if( e.Element.Name != "Hobbies")
        {
            return;
        }
    
        var target = (MyData) e.ObjectBeingDeserialized;
        foreach(XmlElement hobby in e.Element.ChildNodes)
        {
            target.Hobbies.Add(hobby.InnerText);
            target.HobbyData.Add(new Hobby{Name = hobby.InnerText});
        }
    }
    

提交回复
热议问题