简体   繁体   中英

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.

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;
}
  XDocument doc= XDocument.Load(pathToXmlFilename);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM