mandag 9. november 2009

XmlSerializer

Every project these days tend to deal with some kind of serialization. I've Created a small pice of code to make my world simpler. How to create a Generic XmlSerializer.
public static class GenericXmlSerializer { public static T Deserialize(string xml) { var serializer = new XmlSerializer(typeof(T)); using (var sr = new StringReader(xml)) { return (T)serializer.Deserialize(sr); } } public static string Serialize(T source) { var serializer = new XmlSerializer(typeof(T)); using (var sr = new StringWriter()) { serializer.Serialize(sr, source); return sr.ToString(); } } }
My next problem is how to run my code. I've created a small example class for my example
public class Item
  {
  public string Name
  {get; set;}

  [XmlElement]
  public string[] Email
  { get; set; }

}
My production code for serialize/deserialize an instance of Item is displayed below.
--Serialize
var item = new Item {Name = "Authovr", Email = new string[] {"author1@gmail.com", "author2@gmail.com"}};
var xml = GenericXmlSerializer.Serialize(item);
--Deserialize
var xml = "<item><name>Author</name><email>author1@gmail.com</email><email>author2@gmail.com</email></item>";
var item = GenericXmlSerializer.Deserialize(xml);
Note!!
My example includes serializing an Array element. Using the XmlElement atteribute makes the serialization nice and readable.

Ingen kommentarer:

Legg inn en kommentar