Reputation: 63
Objects of the following class can be serialized to XML as intended, as long as the actual type of the generic field Object
is contained in the list of XmlElement
attributes:
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;
}
}
The question is:
How can I serialize an object of this class, including the generic field Object
without specifiying all possible types for T
in XmlElement
attributes?
Upvotes: 6
Views: 6717
Reputation: 2780
I ran into this too. What I did is create a wrapper class:
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;
}
Here is the class used to wrap the object
[XmlRoot("Root")]
public class SerializeWrapper<TObject>
{
[XmlAttribute()]
public string Name { get; set; }
public TObject XmlObject { get; set; }
}
Now, you can just call it as:
Weapon weapon = new Weapon()
var xdoc = SerializeToXmlDocument<Weapon>(weapon);
Upvotes: 2