[英]Deserialise XML array at document root
Yet another question about XML serialisation with .Net. 关于.Net的XML序列化的另一个问题。
I'm receiving an XML string from a 3rd party and want to parse it into a .Net class with minimum of fuss. 我从第三方收到一个XML字符串,并希望将其解析为.Net类,而不用大惊小怪。 I don't want to use xsd as my XML is pretty simple and I don't like the verbose classes it spits out.
我不想使用xsd,因为我的XML非常简单,我不喜欢它吐出的冗长类。 I've got the basics of the deserialisation working but am struggling with a root level array.
我已经得到了反序列化的基础知识,但我正在努力使用根级别数组。
The problem XML is as below: 问题XML如下:
<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? 如何映射C#People类的属性以对其进行反序列化?
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: 如果我将XML修改为:
<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: 因为这有:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.