Destroy the XML array at the root of the document

Another question about serializing XML with .Net.

I get an XML string from a third party and want to parse it into a .Net class with a minimal amount of fuss. I don't want to use xsd since my XML is pretty simple and I don't like the detailed classes that it spits out. I have the basics of deserialization work, but I'm struggling with an array of root level.

The XML problem is as follows:

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

How to map C # People class attributes for deserialization?

This is what I would like to work, but it is not.

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

If I use XML for:

 <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; } 
+8
c # xml-serialization
source share
1 answer
 [XmlElement("person")] public List<Person> Persons; 

although I prefer:

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

how does this take place:

  • creating a deferred list when you don't need people
  • no "set" in the list property (it is not needed)
+9
source share

All Articles