C# Generic XML Serialization
This example is the steps to serialize and deserialize an object as XML data. The sample generic class will only serialize “public” properties of a class.
Usage:
CSharpCodeExampleData exData = new CSharpCodeExampleData();
exData.Name = "Popular C# Examples Web Site";
exData.Url = "http://www.csharpexamples.com";
exData.AttributeWillBeIgnore = "This value won't be serialized";
GenericXMLSerializer<CSharpCodeExampleData> serializer = new GenericXMLSerializer<CSharpCodeExampleData>();
//Serialize
string xml = serializer.Serialize(exData);
//Deserialize
CSharpCodeExampleData deserilizedObject = serializer.Deserialize(xml);
Generic Code:
public class GenericXMLSerializer<T>
{
///
/// Serializes the specified object and returns the xml value
///
///
///
public string Serialize(T obj)
{
string result = string.Empty;
System.IO.StringWriter writer = new System.IO.StringWriter();
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
serializer.Serialize(writer, obj);
result = writer.ToString();
return result;
}
///
/// Deserializes the XML content to a specified object
///
///
///
public T Deserialize(string xml)
{
T result = default(T);
if (!string.IsNullOrEmpty(xml))
{
System.IO.TextReader tr = new System.IO.StringReader(xml);
System.Xml.XmlReader reader = System.Xml.XmlReader.Create(tr);
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
if (serializer.CanDeserialize(reader))
result = (T)serializer.Deserialize(reader);
}
return result;
}
}
///
/// class example which will be serialized
///
public class CSharpCodeExampleData
{
[XmlAttribute("Url")]
public string Url = null;
[XmlAttribute("Name")]
public string Name = null;
[XmlIgnore]
public string AttributeWillBeIgnore = null;
}