Daniel Revell
Daniel Revell

Reputation: 8586

Deserializing XML to class when the property name is an attribute on each node

I'm attempting to integrate with a 3rd party REST API. This API always returns all of it's resources as type Asset and it's properties as type Attribute. It uses an attribute on the Attribute nodes to supply the property name. The xml reads as follows:

<Assets>
    <Asset>
        <Attribute name="AssetType">Story</Attribute>
        <Attribute name="OwnerName">Fred Blogs</Attribute>
        <Attribute name="Name">The Lord of the Rings</Attribute>
        ...
    </Asset>
    ...
</Assets>

I would like to use DataContractSerializer (or XmlSerializer possibly?) to convert this to a list of pocos of type Story.

[DataContract(Name="Asset")]
    public class Story
    {
        public string OwnerName { get; set; }
        public string Name { get; set; }
    }

The DataMember attribute works on the name of the node, not the value of a nodes attribute as far as I can tell. Is there a way to get round this?

I'd like to end up with a WebAPI client reading as such..

    var client = new HttpClient();
    var result = client.GetAsync(uri).Result;
    var stories = r.Content.ReadAsAsync<List<Story>>().Result;

Upvotes: 0

Views: 545

Answers (2)

Oscar
Oscar

Reputation: 13970

You will have to write a custom serializer to achieve this. See more info here:

http://msdn.microsoft.com/en-us/library/ty01x675(v=vs.80).aspx

Upvotes: 1

L.B
L.B

Reputation: 116168

How about parsing it with Linq2Xml?

XDocument xDoc = XDocument.Parse(xml);
var assets = xDoc.Descendants("Asset")
                    .Select(a=>a.Descendants("Attribute")
                                .ToDictionary(x => x.Attribute("name").Value, 
                                              x => x.Value))
                    .ToList();

Upvotes: 1

Related Questions