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;
}
[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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With