如何反序列化此XML文件?

时间:2012-12-09 22:35:40

标签: c# xml xml-serialization xml-deserialization

我需要从这个XML文件中获取数据,我认为反序列化将是可行的方法,但是,我不知道如何使用.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>

基本上,我希望能够随时获取每个控制台的年份或制造商数据。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

  XDocument doc= XDocument.Load(pathToXmlFilename);

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