Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this too ... hacky? Xml to an object

Tags:

c#

xml

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.

like image 422
jeriley Avatar asked Dec 06 '22 01:12

jeriley


1 Answers

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();
    }
}
like image 159
Wallace Breza Avatar answered Dec 08 '22 01:12

Wallace Breza