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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With