2013-05-09 92 views
0

你好可以有人請告訴我如何讓閱讀這個XML在C#工作正常,我已經嘗試了很多,我不能得到它的工作,非常感謝幫助!閱讀xml從PHP到C#

我創建這個XML在PHP中:

<?xml version="1.0" ?> 
- <root> 
    <budget>n/A</budget> 
    <cast>Robert De Niro/Katherine Heigl/Diane Keaton/Amanda Seyfried/Topher Grace/Susan Sarandon/Robin Williams/Ben Barnes/Christine Ebersole/David Rasche/Patricia Rae/Ana Ayora/Kyle Bornheimer/Megan Ketch/Christa Campbell</cast> 
    <country>USA</country> 
    <directors>Justin Zackham</directors> 
    <genres>Comedy</genres> 
    <languages>English/Spanish</languages> 
    <discription>A long-divorced couple fakes being married as their family unites for a wedding.</discription> 
    <plot>A long-divorced couple fakes being married as their family unites for a wedding.</plot> 
    <trailer>http://www.imdb.com/video/imdb/vi2079761945/player</trailer> 
    <poster>posters/1931435.jpg</poster> 
    <rating>5.2</rating> 
    <releasedate>26 April 2013 (USA)</releasedate> 
    <runtime>89 min</runtime> 
    <title>It's never too late to start acting like a family.</title> 
    <tagline>It's never too late to start acting like a family.</tagline> 
    <year>2013</year> 
    <votes>1,466</votes> 
    <url>http://www.imdb.com/title/tt1931435/</url> 
    <sites><a href="http://facebook.com/TheBigWeddingMovie" target="_blank">Official Facebook</a>/<a href="http://thebigweddingmovie.com/" target="_blank">Official site</a></sites> 
    </root> 

我試圖解析它在C#這樣的:

     using (XmlReader reader = XmlReader.Create("data.xml")) 
         { 
          reader.ReadStartElement("root"); 
          while (reader.Name == "title") 
          { 
           XElement el = (XElement)XNode.ReadFrom(reader); 
          } 

          reader.ReadEndElement(); 
         } 

任何人都可以看到我在做什麼錯在這裏?

我的結果中沒有標題。

怎麼了?

回答

1

因爲你的XML是平的,有關使用LINQ並將其加載到字典

var response = new WebClient().DownloadString("http://citfree.com/cronjobs/imdb/fetch.php?url=Star+Wars"); 

var dict = XDocument.Parse(response.Trim()).Root 
      .Elements() 
      .ToDictionary(e => e.Name.LocalName, e => (string)e); 

Console.WriteLine(dict["budget"]); 

PS如何:要直接從文件中讀取,你可以使用XDocument.Load(filename)

+0

我試過這個,但得到了網絡異常 var response = new WebClient()。DownloadString(「http://www.citfree.com/cronjobs/imdb/fetch.php?url=」+ IMDB); var doc = XDocument.Parse(response).Root.Elements(); var dict = doc.ToDictionary(e => e.Name.LocalName,e =>(string)e); Console.WriteLine(dict [「budget」]); – Dean 2013-05-09 10:02:59

+0

@Dean查看最新的答案。我添加了一個'Trim',因爲你的網站在xml中預先設置了一個空行。 – I4V 2013-05-09 10:28:06

1

所以,你想在C#中有一個對象來保存XML表示?

試試這個:

XDocument doc = XDocument.Load("data.xml"); 
+0

即時得到異常。 – Dean 2013-05-09 10:03:25

+0

你能否更新你的問題並提供你當前的源代碼? – Jan 2013-05-09 10:50:41