Loading...
 
JoiWiki » Developer » .Net » .Net Snippets » Serialise Object to XML Serialise Object to XML

Serialise Object to XML

Serialise Object to XML

This is a nice quick snippet - here's some code for you to use if you need to escape an object to XML - personally I've used it to show an object through a debugging out function for a website but I've a feeling that it will be used a lot more moving forwards:

 

 

public string ToXML(object _ToSerialise)
{
  using (var stringwriter = new System.IO.StringWriter())
  {
    var serializer = new System.Xml.Serialization.XmlSerializer(_ToSerialise.GetType());
    serializer.Serialize(stringwriter, _ToSerialise);
    return stringwriter.ToString();
  };
}

 

I've not played with the following all that much but why wouldn't you want to go the other way around as well?

 

public T LoadFromXMLString(string xmlText){
  using (var stringReader = new System.IO.StringReader(xmlText))
  {
    var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
    return (T)serializer.Deserialize(stringReader);
  };}

 

 

 

 

Created by JBaker. Last Modification: Friday May 10, 2019 13:15:28 BST by JBaker.

Developer