Convert an object to an XML string
Here are conversion method for both ways.this = instance of your class
public string ToXML() { using(var stringwriter = new System.IO.StringWriter()) { var serializer = new XmlSerializer(this.GetType()); serializer.Serialize(stringwriter, this); return stringwriter.ToString(); } } public static YourClass LoadFromXMLString(string xmlText) { using(var stringReader = new System.IO.StringReader(xmlText)) { var serializer = new XmlSerializer(typeof(YourClass )); return serializer.Deserialize(stringReader) as YourClass ; } }
I realize this is a very old post, but after looking at L.B's response I thought about how I could improve upon the accepted answer and make it generic for my own application. Here's what I came up with:
public static string Serialize<T>(T dataToSerialize){ try { var stringwriter = new System.IO.StringWriter(); var serializer = new XmlSerializer(typeof(T)); serializer.Serialize(stringwriter, dataToSerialize); return stringwriter.ToString(); } catch { throw; }}public static T Deserialize<T>(string xmlText){ try { var stringReader = new System.IO.StringReader(xmlText); var serializer = new XmlSerializer(typeof(T)); return (T)serializer.Deserialize(stringReader); } catch { throw; }}
These methods can now be placed in a static helper class, which means no code duplication to every class that needs to be serialized.
public static string Serialize(object dataToSerialize) { if(dataToSerialize==null) return null; using (StringWriter stringwriter = new System.IO.StringWriter()) { var serializer = new XmlSerializer(dataToSerialize.GetType()); serializer.Serialize(stringwriter, dataToSerialize); return stringwriter.ToString(); } } public static T Deserialize<T>(string xmlText) { if(String.IsNullOrWhiteSpace(xmlText)) return default(T); using (StringReader stringReader = new System.IO.StringReader(xmlText)) { var serializer = new XmlSerializer(typeof(T)); return (T)serializer.Deserialize(stringReader); } }