0

I have some XML that I need to deserialise

<element>
  <childElement key="myKey1">a value</childElement>
  <childElement key="myKey2">another value</childElement>
</element>

Into a class like

[XmlRoot(ElementName="element")]
public class Element
{
  public string MyKey1 { get; set; }
  public string MyKey2 { get; set; }
}

Is it possible for me to annotate MyKey1 and MyKey2 so that if the xml above is deserialised then MyKey1 will be "a value" and MyKey2 will equal "another value"? If not then what is the best approach to deserialising attributes like this?

Jim Jeffries
  • 9,841
  • 15
  • 62
  • 103
  • possible duplicate of [XML De-serialize into type based on attribute](http://stackoverflow.com/questions/9482354/xml-de-serialize-into-type-based-on-attribute) – Preet Sangha Apr 22 '13 at 13:02
  • @PreetaSangha That is a slightly different case. They want to use different elements based on the attributes. I want to use the value in the attribute as the element name – Jim Jeffries Apr 22 '13 at 13:08
  • what about : http://stackoverflow.com/questions/1755178/how-can-i-deserialise-an-xml-element-into-an-array-of-elements-with-both-attribu?rq=1 – Preet Sangha Apr 22 '13 at 13:10
  • @PreetSangha similar, but also slightly different. – Jim Jeffries Apr 22 '13 at 13:12

1 Answers1

1

You can use XmlAttribute attribute but your xml seems better to fit to a Dictionary<string,string>

Using Linq To Xml

string xml = @"<element>
    <childElement key=""myKey1"">a value</childElement>
    <childElement key=""myKey2"">another value</childElement>
</element>";

var xDoc = XDocument.Parse(xml);
var dict = xDoc.Descendants("childElement")
               .ToDictionary(x => x.Attribute("key").Value, x => x.Value);

Console.WriteLine(dict["myKey1"]);
I4V
  • 34,891
  • 6
  • 67
  • 79
  • That's great thanks, only a little bit more code, but probably more obvious than any complicated attribute based approach. – Jim Jeffries Apr 22 '13 at 14:01