chyyran
chyyran

Reputation: 2626

How do I deserialize this XML file?

I need to get the data from this XML file, and I think deserializing it would be the way to go, however, I have no idea how to do that with .NET.

<consoles>
    <console name ="snes">
        <year>1991</year>
        <manufacturer>Nintendo</manufacturer>
    </console>
    <console name = "wii">
        <year>2006</year>
        <manufacturer>Nintendo</manufacturer>
    </console>
    <console name = "ps3">
        <year>2006</year>
        <manufacturer>Sony</manufacturer>
    </console>
</consoles>

Basically, I want to be able to at will get the year or manufacturer data for each console.

Upvotes: 0

Views: 116

Answers (2)

L.B
L.B

Reputation: 116138

XmlSerializer ser = new XmlSerializer(typeof(console[]),new XmlRootAttribute("consoles"));
var consoles = (console[])ser.Deserialize(stream);


public class console
{
    [XmlAttribute]
    public string name;
    public int year;
    public string manufacturer;
}

Upvotes: 2

Vlad
Vlad

Reputation: 878

  XDocument doc= XDocument.Load(pathToXmlFilename);

  foreach(XElement element in doc.Root.Elements("console"))
  {
     Console.WriteLine(element.Element("year").Value);
  }

Upvotes: 0

Related Questions