tags:

views:

157

answers:

2

I'm playing with my favorite thing, xml (have the decency to kill me please) and the ultimate goal is save it in-house and use the data in a different manner (this is an export from another system). I've got goo that works, but meh, I think it can be a lot better.

    public Position(XElement element)
    {
        Id = element.GetElementByName("id");
        Title = element.GetElementByName("title");
    }

I'm thinking of making it more automated (hacky) by adding data annotations for the xml element it represents. Something like this for instance.

    [XmlElement("id")]
    public string Id { get; set; }

    [XmlElement("title")]
    public string Title { get; set; }

then writing some reflection/mapper code but both ways feels ... dirty. Should I care? Is there a better way? Maybe deserialize is the right approach? I just have a feeling there's a mo' bettah way to do this.

+13  A: 

You can use the XmlSerializer class and markup your class properties with attributes to control the serialization and deserialization of the objects.

Here's a simple method you can use to deserialize your XDocument into your object:

public static T DeserializeXml<T>(XDocument document)
{
    using (var reader = document.CreateReader())
    {
        var serializer = new XmlSerializer(typeof (T));
        return (T) serializer.Deserialize(reader);
    }
}

and a simple serializer method:

public static String ToXml<T>(T instance)
{
    using (var output = new StringWriter(new StringBuilder()))
    {
        var serializer = new XmlSerializer(typeof(T));
        serializer.Serialize(output, instance);

        return output.ToString();
    }
}
Wallace Breza
I used the xsd as Kragen mentioned (to cheat) and got an idea of how they structured their attributes for nested ojbects, and slightly modified your first method to take in a string value, then used XDoc to parse it inside. Works nicely.
jeriley
@jeriley - Glad to hear :)
Wallace Breza
+3  A: 

The mechanism that you are suggesting already exists in the form of the XmlSerializer class and a set of custom attributes that you can use to control the serialisation process.

In fact the .Net framework comes with a tool xsd.exe which will generate these class files for you from a schema definition (.xsd) file.

Also, just to make things really easy, Visual Studio even has the ability to generate you an .xsd schema for an xml snippet (its hidden away in the Xml menu somewhere).

Kragen