Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialise XML array at document root

Yet another question about XML serialisation with .Net.

I'm receiving an XML string from a 3rd party and want to parse it into a .Net class with minimum of fuss. I don't want to use xsd as my XML is pretty simple and I don't like the verbose classes it spits out. I've got the basics of the deserialisation working but am struggling with a root level array.

The problem XML is as below:

<people>
  <person>
    <id>1234</id>
  </person>
  <person>
    <id>4567</id>
  </person>
 </people>

How do I map the attributes on my C# People class to deserialise it?

This is what I'd like to work but it doesn't.

[Serializable()]
[XmlRootAttribute("people", Namespace = "", IsNullable = false)]
public class People
{
    [XmlArrayItem(typeof(Person), ElementName = "person")]
    public List<Person> Persons;
}

If I mangle the XML to:

<result>
  <people>
    <person>
      <id>1234</id>
    </person>
    <person>
      <id>4567</id>
    </person>
   </people>
 </result>

Then it works with the class definition below but it feels very wrong.

[Serializable()]
[XmlRootAttribute("result", Namespace = "", IsNullable = false)]
public class People
{
    [XmlArray(ElementName = "people")]
    [XmlArrayItem(typeof(Person), ElementName = "person")]
    public List<Person> Persons;
}
like image 636
sipsorcery Avatar asked Jan 29 '11 13:01

sipsorcery


1 Answers

[XmlElement("person")]
public List<Person> Persons;

although actually I prefer:

private List<Person> persons;
[XmlElement("person")]
public List<Person> Persons {get{return persons??(persons=new List<Person>());}}

as this has:

  • deferred list creation, for when you don't need any people
  • no "set" on the list property (it isn't needed)
like image 188
Marc Gravell Avatar answered Sep 17 '22 22:09

Marc Gravell