要排序为此格式的类布局

mrb*_*lah 1 .net c# xml-serialization

我的XML看起来像这样:

<cars year="2009">
   <engineType name="blah">
      <part type="metal"></part>
   </engineType>
   <makes>
      <make name="honda" id="1">
         <models>
            <model name="accord" id="2"/>
         </models>
      </make>
   </makes>
</cars>
Run Code Online (Sandbox Code Playgroud)

如何创建一个在反序列化时生成上述xml布局的类.

Rex*_*x M 10

XML序列化的灵活性来自属性和IXmlSerializable.XmlRoot,XmlElement,XmlAttribute是一些很容易将序列化程序指向一些常见但有用的方向.没有更多信息,它可能看起来像这样:

[XmlRoot("cars")]
public class Cars
{
    [XmlAttribute("year")]
    public int Year {get;set;}

    [XmlElement("engineType")]
    public EngineType EngineType {get;set;}

    [XmlElement("makes")]
    public List<Make> Makes {get;set;}
}

public class EngineType
{
    [XmlAttribute("name")]
    public string Name {get;set;}

    [XmlElement("part")]
    public Part Part {get;set;}
}

public class Make
{
    [XmlAttribute("name")]
    public string Name {get;set;}

    [XmlAttribute("id")]
    public int ID {get;set;}

    [XmlElement("models")]
    public List<Model> Models {get;set;}
}

public class Model
{
    [XmlAttribute("name")]
    public string Name {get;set;}

    [XmlAttribute("id")]
    public int ID {get;set;}
}
Run Code Online (Sandbox Code Playgroud)