问题
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