2009-09-21 25 views
1

我的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布局。

回答

10

XML序列化的灵活性来自于属性和IXmlSerializableXmlRoot,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;} 
}