views:

217

answers:

2

Say I've a class (model) called Instance with Properties DatbaseHostname, AccessManagerHostname, DatabaseUsername and DatabasePassword

public class Instance
{
    private string _DatabaseHostname;

    public string DatabaseHostname
    {
        get { return _DatabaseHostname; }
        set { _DatabaseHostname = value; }
    }
    private string _AccessManagerHostname;

    public string AccessManagerHostname
    {
        get { return _AccessManagerHostname; }
        set { _AccessManagerHostname = value; }
    }
    private string _DatabaseUsername;

    public string DatabaseUsername
    {
        get { return _DatabaseUsername; }
        set { _DatabaseUsername = value; }
    }

    private string _DatabasePassword;

    public string DatabasePassword
    {
        get { return _DatabasePassword; }
        set { _DatabasePassword = value; }
    }
}

I'm looking for a sample code to read/write this Model to XML (preferably linq2XML) => storing 1:n instances in XML. i can manage the the view and ViewModel part myself, although it would be nice if someone had a sample of that part too..

A: 

Not sure how you want your xml structured, but this should work:

    List<Instance> instances = new List<Instance>();
    // Get your instances here...

    var baseNode = new XElement("Instances");

    instances.ForEach(instance => baseNode.Add("Instance",
        new XAttribute("DatabaseHostname", instance.DatabaseHostname),
        new XAttribute("AccessManagerHostname", instance.AccessManagerHostname),
        new XAttribute("DatabaseUsername", instance.DatabaseUsername),
        new XAttribute("DatabasePassword", instance.DatabasePassword)));
pduncan
+1  A: 

Well, you could use Linq to XML, but your class is a perfect candidate for XML Serialization, which is much simpler IMHO :

var list = new List<Instance>();
...

// Serialization

var xs = new XmlSerializer(typeof(List<Instance>));
using (var writer = XmlWriter.Create(filename))
{
    xs.Serialize(writer, list);
}

...

// Deserialization

using (var reader = XmlReader.Create(filename))
{
    list = xs.Deserialize(reader) as List<Instance>;
}
Thomas Levesque
good idea, thanks!
Christian