XmlConverter - serialize/deserialize an object to/from Xml (continue)
Few days ago I wrote about a static class named XmlConverter. It contains few generic methods which allow an object to be serialized to XML or deserialized from XML. Today, I rewrite it to a XML utility class with extension methods. The following snippet contains the new class.
[sourcecode language="csharp"]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
namespace XmlConverter.Utilities
{
public static class XmlUtils
{
public static string ToXml
where T : new()
{
return ToXml
}
public static string ToXml
where T : new()
{
try
{
using (MemoryStream stream = new MemoryStream())
{
using (TextWriter writer = new StreamWriter(stream, encoding))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(writer, value);
int cnt = (int)stream.Length;
byte[] arr = new byte[cnt];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, cnt);
return encoding.GetString(arr, 0, arr.Length).Trim();
}
}
}
catch
{
}
return null;
}
public static T FromXml
where T : new()
{
try
{
using (StringReader stream = new StringReader(xml))
{
using (XmlTextReader reader = new XmlTextReader(stream))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(reader);
}
}
}
catch
{
}
return default(T);
}
}
}
[/sourcecode]
Contact, List<Contact> object and XML output for them are the same as those in my old post. Now an object can be serialized/deserialized in this way:
[sourcecode language="csharp"]
// Serialize the list of Contact objects
var listXml = list.ToXml();
// Deserialize the list of Contact objects
List
restoredList = restoredList.FromXml(listXml);
// Serialize Contact object
var contactXml = contact.ToXml();
// Deserialize Contact object
Contact restoredContact = new Contact();
restoredContact = restoredContact.FromXml(contactXml);
[/sourcecode]
A using statement to extension methods class’ name space is required in order to access them.
[sourcecode language="csharp"]using XmlConverter.Utilities;[/sourcecode]
July 10th, 2008 at 5:50 pm
[...] is an implementation using VB.Net of XmlUtils class from my old post. Yesterday, I wrote an implementation of XmlConverter using VB.Net. As I wrote the idea is to [...]
March 16th, 2009 at 11:01 pm
[...] XmlConverter - serialize/deserialize an object to/from Xml (continue) [...]