如何将泛型类序列化为XML?

时间:2012-02-22 15:27:01

标签: c# generics xml-serialization

只要通用字段Object的实际类型包含在XmlElement属性列表中,就可以将以下类的对象序列化为XML:

public class SerializedObject<T> : Serializable where T : Serializable
{
    [System.Xml.Serialization.XmlElement(Type = typeof(Weapon))]
    [System.Xml.Serialization.XmlElement(Type = typeof(Armor))]
    [System.Xml.Serialization.XmlElement(Type = typeof(QuestItem))]
    public T Object;

    public string ObjectId;
    public int ID;

    public SerializedObject() { }

    public SerializedObject(T _object)
    {
        Object = _object;
        ID = Object.Id;
        ObjectId = Object.ObjectId;
    }
}

问题是:

如何序列化此类的对象,包括通用字段Object,而不指定T属性中XmlElement的所有可能类型?

1 个答案:

答案 0 :(得分:2)

我也碰到了这个。我所做的是创建一个包装类:

public static XmlDocument SerializeToXmlDocument<XmlEntity>(XmlEntity o)
{
    XmlDocument xdoc;
    SerializeWrapper<XmlEntity> wrapper = new SerializeWrapper<XmlEntity>();
    wrapper.XmlObject = o;

    XmlSerializer xs = new XmlSerializer(wrapper.GetType());
    using (MemoryStream ms = new MemoryStream())
    {
        xs.Serialize(ms, wrapper);
        xdoc = new XmlDocument();
        ms.Position = 0;
        xdoc.Load(ms);
    }

    return xdoc;
}

这是用于包装对象的类

[XmlRoot("Root")]
public class SerializeWrapper<TObject>
{
    [XmlAttribute()]
    public string Name { get; set; }

    public TObject XmlObject { get; set; }
}

现在,您可以将其称为:

Weapon weapon = new Weapon()
var xdoc = SerializeToXmlDocument<Weapon>(weapon);