5

I have the following XML

<map version="1.0">
    <properties>
        <property name="color" value="blue" />
        <property name="size" value="huge" />
        <property name="texture" value="rugged" />
    </properties>
</map>

I am trying to write classes that I can deserialize this into, this is what I have:

[XmlRoot("map")]
public class MyMap
{
    [XmlAttribute("version")]
    public decimal Version { get; set; }
    [XmlElement("properties")]
    public List<MyProperty> Properties { get; set; }
}

public class MyProperty
{
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlAttribute("value")]
    public string Value { get; set; }
}

The problem is that I cant seem to read the property list, I just get one entry and it has null in both Name and Value.

Are there some magic attributes I need to set to get this to work?

cadrell0
  • 17,109
  • 5
  • 51
  • 69
Toodleey
  • 913
  • 1
  • 8
  • 22
  • If the above is all the XML you have, then it is invalid, and I'm surprised it is deserializing at all. – Tejs Apr 24 '12 at 18:46

3 Answers3

14

You should change MyMap as below. XmlArray and XmlArrayItem are the magic attributes

[XmlRoot("map")]
public class MyMap
{
    [XmlAttribute("version")]
    public decimal Version { get; set; }
    [XmlArray("properties")]
    [XmlArrayItem("property")]
    public List<MyProperty> Properties { get; set; }
}
L.B
  • 114,136
  • 19
  • 178
  • 224
  • Brilliant, that worked perfectly. If someone knows of a good tutorial on these attributes and how they work I would appreciate it. All i find are copy/pastes of very simple ones. – Toodleey Apr 24 '12 at 19:40
  • Still very relevant. Caught me for about 2 hours today. Couldn't figure it out. Thanks very much – Seamus Barrett Jan 23 '18 at 17:02
2

Instead of XmlElement, try:

[XmlArray("Properties")]

...on the List<> property.

Amadeus Hein
  • 706
  • 1
  • 4
  • 12
1

One way to find a solution would be to populate the object in code and then serialize it to xml, and see what the schema looks like. Also you could use xsd.exe to autogenerate your classes.

therealmitchconnors
  • 2,732
  • 1
  • 18
  • 36