Francis Gilbert
Francis Gilbert

Reputation: 3442

Deserializing Xml which has the same element name but different attributes

I have some XML which looks like this:

<Stat Type="first_name">[Value]</Stat>
<Stat Type="last_name">[Value]</Stat>
<Stat Type="known_name">[Value]</Stat>

I want to deserialize this to an object. As there is one element name called "Stat" it's making it difficult to get something like:

[XmlAttribute("first_name")]
public string FirstName{get;set;}

[XmlAttribute("last_name")]
public string LastName{get;set;}

[XmlAttribute("known_name")]
public string KnownName{get;set;}

Is there a way of getting the XML above into an object like:

public string FirstName{get;set;}
public string LastName{get;set;}
public string KnownName{get;set;}

Thanks.

Upvotes: 2

Views: 1806

Answers (3)

Francis Gilbert
Francis Gilbert

Reputation: 3442

I managed to solve this by using an extension. Not ideal. I get the list of stats:

[XmlElement("Stat")]
public List<Stat> Stats { get; set;}

Then I have separate properties like:

public string FirstName
{
   get { return Stats.GetStat("first_name"); }
}

The GetStat extension method on the Stats property then gets the relevant key. Unfortunately, this way, it will run through that list for each property I want to get.

public static string GetStat(this List<Stat> stats, string key)
{
  var val = stats.FirstOrDefault(item => item.Type == key);

  if (val != null)
    return val.Value ?? String.Empty;
  return String.Empty;
} 

Upvotes: 2

Bartlett
Bartlett

Reputation: 934

If you want to use serialization I think you will need an intermediate object. So, deserialize into something like this:

public class Stat
{
    [XmlAttribute("Type")]
    public string Type { get; set; }

    [XmlText]
    public string Value { get; set; }
}

Then write some code to flatten into the shape you want.

Upvotes: 1

Andrew Bullock
Andrew Bullock

Reputation: 37426

you'll probably have to parse the XML yourself with XPath or something. Mines a bit rusty, but its something like:

var stat = xmlDocument.DocumentElement.GetSingleNode("stat[@type='first_name']");
var value = stat.InnerText;

Upvotes: 0

Related Questions