This is one of those helper classes that I keep using very often.
using System.IO;
using System.Text;
using System.Xml.Serialization;
public class XmlSerializationHelper<T> where T : class
{
public string Serialize(T objectToSerialize)
{
var sb = new StringBuilder();
var serializer = new XmlSerializer(typeof(T));
using (var writer = new StringWriter(sb))
{
serializer.Serialize(writer, objectToSerialize);
}
return sb.ToString();
}
public T Deserialize(string xml)
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(new StringReader(xml));
}
}
Usage:
string xml = new XmlSerializationHelper<SomeClass>().Serialize(obj);
AND
SomeClass obj = new XmlSerializationHelper<SomeClass>().Deserialize(xml);
Note: I am not using var here, just so that its clear what the return types are.
using System.IO;
using System.Text;
using System.Xml.Serialization;
public class XmlSerializationHelper<T> where T : class
{
public string Serialize(T objectToSerialize)
{
var sb = new StringBuilder();
var serializer = new XmlSerializer(typeof(T));
using (var writer = new StringWriter(sb))
{
serializer.Serialize(writer, objectToSerialize);
}
return sb.ToString();
}
public T Deserialize(string xml)
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(new StringReader(xml));
}
}
Usage:
string xml = new XmlSerializationHelper<SomeClass>().Serialize(obj);
AND
SomeClass obj = new XmlSerializationHelper<SomeClass>().Deserialize(xml);
Note: I am not using var here, just so that its clear what the return types are.
No comments:
Post a Comment