As code above from Lance McCarthy:
[DataContract]
public class Foo
{
[DataMember]
public string SomeText { get; set; }
// ....
[IgnoreDataMember]
public string FizzBuzz { get; set; }
}
In addition you can use my own extension (!!! Change MemoryStream to FileStream if you need to save it to file instead of to string):
public static class Extensions
{
public static string Serialize<T>(this T obj)
{
var ms = new MemoryStream();
// Write an object to the Stream and leave it opened
using (var writer = XmlDictionaryWriter.CreateTextWriter(ms, Encoding.UTF8, ownsStream: false))
{
var ser = new DataContractSerializer(typeof(T));
ser.WriteObject(writer, obj);
}
// Read serialized string from Stream and close it
using (var reader = new StreamReader(ms, Encoding.UTF8))
{
ms.Position = 0;
return reader.ReadToEnd();
}
}
public static T Deserialize<T>(this string xml)
{
var ms = new MemoryStream();
// Write xml content to the Stream and leave it opened
using (var writer = new StreamWriter(ms, Encoding.UTF8, 512, leaveOpen: true))
{
writer.Write(xml);
writer.Flush();
ms.Position = 0;
}
// Read Stream to the Serializer and Deserialize and close it
using (var reader = XmlDictionaryReader.CreateTextReader(ms, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null))
{
var ser = new DataContractSerializer(typeof(T));
return (T)ser.ReadObject(reader);
}
}
}
and then just use those extentions:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestSerializer()
{
var obj = new Foo()
{
SomeText = "Sample String",
SomeNumber = 135,
SomeDate = DateTime.Now,
SomeBool = true,
};
// Try to serialize to string
string xml = obj.Serialize();
// Try to deserialize from string
var newObj = xml.Deserialize<Foo>();
Assert.AreEqual(obj.SomeText, newObj.SomeText);
Assert.AreEqual(obj.SomeNumber, newObj.SomeNumber);
Assert.AreEqual(obj.SomeDate, newObj.SomeDate);
Assert.AreEqual(obj.SomeBool, newObj.SomeBool);
}
}
Good luck mate.