C#中XML列表对象的反序列化

Thi*_*hat 2 c# xml serialization

我试图在C#中反序列化xml,看起来像这样(缩短版本):

<?xml version="1.0" encoding="UTF-8"?>
<map>
    <parts>
      <part name="default part">
        <objects count="1597">
            <object type="1" symbol="6">
                <coords count="130">
                    <coord x="-221595" y="-109687" flags="1"/>
                    <coord x="-221625" y="-109744"/>
                    <coord x="-221640" y="-109785"/>
                    <coord x="-221640" y="-109841" flags="1"/>
                    <coord x="-221655" y="-109969"/>
                    <coord x="-221655" y="-110040"/>
                    <coord x="-221640" y="-110164" flags="1"/>
                    <coord x="-221640" y="-110209"/>
                    <coord x="-221655" y="-110265"/>
                </coords>
                <pattern rotation="0">
                    <coord x="0" y="0"/>
                </pattern>
            </object>
          </objects>
        </part>
   </parts>
</map>
Run Code Online (Sandbox Code Playgroud)

使用以下类:

[XmlRoot("map")] 
public class Map {


    [XmlElement(ElementName = "parts")]
    public List<Part> parts { get; set; }

    public Map()
    {
         parts = new List<Part>();
    }


public class Part {

    [XmlElement(ElementName = "objects")]
    public List<KdToPostGISProject.Object> objects { get; set; }

    public Part()
    {
        objects = new List<KdToPostGISProject.Object>();
    }

    [XmlAttribute(AttributeName = "name")]
    public String name { get; set; }     

}

public class Object
    {
         [XmlElement(ElementName = "coords")]
         public List<Coord> coords { get; set; } 

          public Object()
          {
             coords = new List<Coord>();
          }
    }


public class Coord
{
    [XmlAttribute]
    public int x { get; set; }
    [XmlAttribute]
    public int y { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

和主要功能:

var serializer = new XmlSerializer(typeof(Map), new XmlRootAttribute("map"));               

Map resultingMessage = (Map)serializer.Deserialize(new FileStream(@"myXml.xml", FileMode.Open));
Run Code Online (Sandbox Code Playgroud)

由于某些原因,我一直试图弄清楚我在零件类中得到的零个对象(和空名称)。现在我被困住了,有任何输入的人吗?

Fun*_*ung 5

对于List<T>成员,您必须将其标记为:

[XmlArray(ElementName = "parts")]
[XmlArrayItem(ElementName = "part")]
public List<Part> parts { get; set; }
Run Code Online (Sandbox Code Playgroud)

不:

[XmlElement(ElementName = "parts")]
Run Code Online (Sandbox Code Playgroud)

更改所有List<T>成员,然后应该可以正常工作。