2012-12-09 147 views
0

我需要從這個XML文件中獲取數據,並且我認爲反序列化它將是一條路,但是我不知道如何使用.NET來做到這一點。如何反序列化此XML文件?

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

我怎麼會去,例如,獲得年度爲Wii與此代碼? – ron975

+0

@ ron975簡單* linq *可以幫助'var year = console.First(c => c.name ==「wii」)。year;' –

0
XDocument doc= XDocument.Load(pathToXmlFilename); 

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