[2005] Serialize any class to Xml and vice-versa
A few classes cannot be serialized to XML because they do not support ISerializable. The most notable being the Dictionary class. However, if it can't serialize, it will just throw an exception about it.
Code:
using System.Xml;
using System.Xml.Serialization;
using System.IO;
public string Serialize<T>(T entity)
{
StringBuilder outputXml = new StringBuilder();
if (typeof(T).IsSerializable)
{
XmlSerializer ser = new XmlSerializer(typeof(T));
using (TextWriter stream = new StringWriter(outputXml))
{
ser.Serialize(stream, entity);
}
return outputXml.ToString();
}
return null;
}
public T Deserialize<T>(string xml)
{
T entity;
if (typeof(T).IsSerializable)
{
XmlSerializer ser = new XmlSerializer(typeof(T));
using (TextReader stream = new StringReader(xml))
{
entity = (T)ser.Deserialize(stream);
}
return entity;
}
return null;
}
Re: [2005] Serialize any class to Xml and vice-versa
Say there object you use this code on, has a list(of T) as one of it's public properties, will it automatically serialize this object properly or would that require writing something recursive to do the job?
Re: [2005] Serialize any class to Xml and vice-versa
It will automatically serialize all properties/objects recursively underneath it (there may be a max depth, but I don't know what it is), assuming the property isn't marked with an [XmlIgnore] attribute tag in the actual class.
Re: [2005] Serialize any class to Xml and vice-versa
Im a bit confused with your original post, is this some sort of question or are you just sharing the code you posted?
If it is a question: You can find out if a type is serializable using the IsSerializable property of the Type class.
Re: [2005] Serialize any class to Xml and vice-versa
This is a codebank forum. it's for posting code.
Re: [2005] Serialize any class to Xml and vice-versa
Yeah, just posting code. The only issue with the code is that some Types cannot be serailized to XML. I think it is because they do not support ISerializable, but I could be wrong. At any rate, if they cannot be serialized, an exception will be thrown alerting you that it cannot be.