Siracuse
Siracuse

Reputation: 551

What is the best way to save a list of objects to an XML file and load that list back using C#?

I have a list of "Gesture" classes in my application:

List<Gesture> gestures = new List<Gesture>();

These gesture classes are pretty simple:

public class Gesture
{
    public String Name { get; set; }
    public List<Point> Points { get; set; }
    public List<Point> TransformedPoints { get; set; }    

    public Gesture(List<Point> Points, String Name)
    {
        this.Points = new List<Point>(Points);
        this.Name = Name;
    }
}

I would like to allow the user to both save the current state of "gestures" to a file and also be able to load a file that contains the data of the gestures.

What is the standard way to do this in C#?

Should I use Serialization? Should I write a class to handle writing/reading this XML file by hand myself? Are there any other ways?

Upvotes: 4

Views: 1242

Answers (4)

Marc Gravell
Marc Gravell

Reputation: 1062865

Yes, that is a very stanadrd scenario for serialization. The only caveat is that I would advise using something "contracts" based, such as XmlSerlializer (or if you want binary instead of xml, protobuf-net). For XmlSerializer, adding a parameterless constructor would be necessary, and you might want to add some xml adornments to control the formatting:

[XmlRoot("gesture")]
public class Gesture
{
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlElement("point")]
    public List<Point> Points { get; set; }
    [XmlElement("transformedPoint")]
    public List<Point> TransformedPoints { get; set; }    
    public Gesture()
    {
        this.Points = new List<Point>();
    }
    public Gesture(List<Point> Points, String Name)
    {
        this.Points = new List<Point>(Points);
        this.Name = Name;
    }
}

Then you could serialize with:

XmlSerializer ser = new XmlSerializer(gestures.GetType());
using(var file = File.Create("gestures.xml")) {
    ser.Serialize(file, gestures);
}
...
using(var file = File.OpenRead("gestures.xml")) {
    gestures = (List<Gesture>) ser.Deserialize(file);
}

Upvotes: 1

David A Moss
David A Moss

Reputation: 239

Check out DataContactSerializer (introduced in .NET 3.0). Depending on what you are doing, it may be a better choice.

Upvotes: 0

Gishu
Gishu

Reputation: 136633

Take a look at XmlSerializer type and XmlSerialization in .net

Here.. found an example that does what you are looking for http://www.switchonthecode.com/tutorials/csharp-tutorial-xml-serialization

Upvotes: 6

Related Questions