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?
XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.
Xml Serializer serializes only public member of object but Binary Serializer serializes all member whether public or private. In Xml Serialization, some of object state is only saved but in Binary Serialization, entire object state is saved.
Serialization of Java Objects to XML can be done using XMLEncoder, XMLDecoder. Java Object Serialization feature was introduced in JDK 1.1. Serialization transforms a Java object or graph of Java object into an array of bytes which can be stored in a file or transmitted over a network.
Serialization is a process by which an object's state is transformed in some serial data format, such as XML or binary format. Deserialization, on the other hand, is used to convert the byte of data, such as XML or binary data, to object type.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With