21 Mayıs 2019, Salı
Ana Sayfa / Her Telden / How to Deserialize XML document

How to Deserialize XML document

Here’s a working version. I changed the XmlElementAttribute labels to XmlElement because in the xml the StockNumber, Make and Model values are elements, not attributes. Also I removed the reader.ReadToEnd(); (that function reads the whole stream and returns a string, so the Deserialze() function couldn’t use the reader anymore…the position was at the end of the stream). I also took a few liberties with the naming :).

Here are the classes:

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

    public string Make { get; set; }

    public string Model { get; set; }

public class CarCollection
    [XmlArrayItem("Car", typeof(Car))]
    public Car[] Car { get; set; }

The Deserialize function:

CarCollection cars = null;
string path = "cars.xml";

XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));

StreamReader reader = new StreamReader(path);
cars = (CarCollection)serializer.Deserialize(reader);

And the slightly tweaked xml (I needed to add a new element to wrap <Cars>…Net is picky about deserializing arrays):

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