Save List<T> to XML file

Here are two methods that we use to accomplish this using the XMLSerializer:

 public static T FromXML<T>(string xml)
 {
     using (StringReader stringReader = new StringReader(xml))
     {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        return (T)serializer.Deserialize(stringReader);
     }
 }

 public string ToXML<T>(T obj)
 {
    using (StringWriter stringWriter = new StringWriter(new StringBuilder()))
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        xmlSerializer.Serialize(stringWriter, obj);
        return stringWriter.ToString();
    }
 }

While you could use a serializer - and many times this is the right answer - I personally would use Linq to XML which would allow you to be more flexible on how your XML should look like, i.e. to create the following XML from a collection foos based on your class:

<Foos>
  <foo Id="1" property1="someprop1" property2="someprop2" />
  <foo Id="1" property1="another" property2="third" />
</Foos>

You could use:

var xml = new XElement("Foos", foos.Select( x=> new XElement("foo", 
                                                new XAttribute("Id", x.Id), 
                                                new XAttribute("property1", x.property1), 
                                                new XAttribute("property2", x.property2))));

Using the code below (Class T Taken from your code snippet) you will be able to serialize into an XML file with ease, and without the hassle of implementing ISerializable

[Serializable()]
public class T
{
    public int Id {get; set;}
    public string property1 {get; set;}
    public string property2 {get; set;}
}

...

List<T> data = new List<T>()

... // populate the list

//create the serialiser to create the xml
XmlSerializer serialiser = new XmlSerializer(typeof(List<T>));

// Create the TextWriter for the serialiser to use
TextWriter filestream = new StreamWriter(@"C:\output.xml");

//write to the file
serialiser.Serialize(filestream , data);

// Close the file
filestream.Close();

Tags:

C#

Xml