C# – How to Deserialize XML document


How do I Deserialize this XML document:

<?xml version="1.0" encoding="utf-8"?>

I have this:

public class Car
    public string StockNumber{ get; set; }

    public string Make{ get; set; }

    public string Model{ get; set; }


[System.Xml.Serialization.XmlRootAttribute("Cars", Namespace = "", IsNullable = false)]
public class Cars
    public Car[] Car { get; set; }



public class CarSerializer
    public Cars Deserialize()
        Cars[] cars = null;
        string path = HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data/") + "cars.xml";

        XmlSerializer serializer = new XmlSerializer(typeof(Cars[]));

        StreamReader reader = new StreamReader(path);
        cars = (Cars[])serializer.Deserialize(reader);

        return cars;

that don't seem to work 🙁

Best Solution

How about you just save the xml to a file, and use xsd to generate C# classes?

  1. Write the file to disk (I named it foo.xml)
  2. Generate the xsd: xsd foo.xml
  3. Generate the C#: xsd foo.xsd /classes

Et voila - and C# code file that should be able to read the data via XmlSerializer:

    XmlSerializer ser = new XmlSerializer(typeof(Cars));
    Cars cars;
    using (XmlReader reader = XmlReader.Create(path))
        cars = (Cars) ser.Deserialize(reader);

(include the generated foo.cs in the project)