XML Serialization quick and easy csharp

Serialization with XML and C#

this is mainly here as a reminder for me on how to do it!

To serialize to a file:


using System.Xml;
using System.Xml.Serialization;
// other code

List<string> mylist = this.getList();

Type stype = typeof(List<string>);

var serializer = new XmlSerializer(stype);
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true; // this is because of microsofts dodgy xml tag
using (var writer = XmlWriter.Create("outputfile.xml",settings))
{
serializer.Serialize(writer,mylist);
}
 

To serialize to a string:

string r = "";
List<string> mylist = this.getList();
   using (MemoryStream memS = new MemoryStream())
    {
      //set up the xml settings
      XmlWriterSettings settings = new XmlWriterSettings();
      settings.OmitXmlDeclaration = true;
      Type stype = typeof(mylist);
      var xmlSerializer = new XmlSerializer(stype);
      StringBuilder retString = new StringBuilder();
      using (XmlWriter writer = XmlTextWriter.Create(memS, settings))
       {
         //write the XML to a stream
         xmlSerializer.Serialize(writer, mylist);
         writer.Close();
       }
    //encode the memory stream to xml
    string v = Encoding.UTF8.GetString(memS.ToArray());
    r = v;             
    memS.Close(); // the using should do this anyway
    }        

To de-serialize xml from a string

public List<string> getMyStrings(string xmlString)
{
 XmlSerializer serializer = new XmlSerializer(typeof(List<string>));
   using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
    {
      return (List<string>)serializer.Deserialize(ms);
    }
}

That’s it, any errors are due to me typing most of it from memory, so if it doesn’t work it’s probably missing a ‘;’ or something

You will need these usings:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>