Deserializing xml to class, trouble with list<>

a 夏天 提交于 2019-12-10 13:57:00

问题


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?


回答1:


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; }
}



回答2:


Instead of XmlElement, try:

[XmlArray("Properties")]

...on the List<> property.




回答3:


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.



来源:https://stackoverflow.com/questions/10304035/deserializing-xml-to-class-trouble-with-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!