views:

64

answers:

2

My XML looks like this:

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

How do I create a class that when deserialized, will product the above xml layout.

+10  A: 

The flexibility of XML serialization comes from attributes and IXmlSerializable. XmlRoot, XmlElement, XmlAttribute are a few that make it very easy to point the serializer in some common but useful directions. Without more information, it might look something like this:

[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;}
}
Rex M
+3  A: 

You can use the XML Schema Definition Tool to automatically generate the class from the XML

Thomas Levesque