要排序为此格式的类布局

时间:2009-09-21 16:12:54

标签: c# .net 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>

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

2 个答案:

答案 0 :(得分:10)

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

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

答案 1 :(得分:3)

您可以使用XML Schema Definition Tool从XML

自动生成类