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.
['https://Stackoverflow.com/questions/3396783', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/202728/']
You can use the [`XmlSerializer`](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx) class and markup your class properties with [attributes](http://msdn.microsoft.com/en-us/library/83y7df3e(VS.71).aspx) 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();
    }
}

```
The mechanism that you are suggesting already exists in the form of the [XmlSerializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx) 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](http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx) 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).