2014-02-13 46 views
0
數據

從Web服務器接收到一個數據我的程序:如何提取XML

<response> 
    <movie> 
     <id>111112</id> 
     <type>serial</type> 
     <title1>movie_title1</title1> 
     <title2>movie_title2</title2> 
     <year>some_year</year> 
     <runtime>some_runtime</runtime> 
     <poster> 
      <small url="url_of_small_poster" /> 
      <medium url="url_of_medium_poster" /> 
      <big url="url_of_big_poster" /> 
     </poster> 
     <url>movies_url</url> 
     <imdb rating="5.0" votes="67" /> 
    </movie> 
    <movie>...</movie>... 
</response> 

我要分析此XML的字符串的所有值,並且把值填補我的課:

public class MoviesClass 
{ 
    String Id{get;set;} 
    String Type{get;set;} 
    String Title1{get;set;} 
    String Title2{get;set;} 
    Int32 Year{get;set;} 
    String SmallPostersURL{get;set;} 
    String MediumPostersURL{get;set;} 
    String BigPostersURL{get;set;} 
    String MoviesURL{get;set;} 
    Single IMDB_Rating{get;set;} 
    Single IMDB_Votes{get;set;} 
} 

我怎麼做到的?我如何使用LINQ獲取這個值?

+0

我只是用這最後一週: https://stackoverflow.com/questions/13073260/extracting-data-from-a-complex-xml-with-linq?rq=1 希望這可以幫助!祝你好運! – user3303858

+1

試試這個http://blog.kushdilip.com/2014/01/converting-csv-to-xml-and-then-to-c.html。首先是CSV到XML,然後是XML到列表。希望這可以幫助。 – kushdilip

回答

1
var xDoc = XDocument.Load("path"); 

var values = 
      xDoc.Descendants("movie") 
       .Select(
        x => 
         new MoviesClass 
         { 
          Id = (string) x.Element("id"), 
          Type = (string) x.Element("type"), 
          Title1 = (string) x.Element("title1"), 
          Title2 = (string) x.Element("title2"), 
          Year = (int)x.Element("year"), 
          Runtime = (string)x.Element("runtime"), 
          SmallPostersURL = (string)x.Element("poster").Element("small").Attribute("url"), 
          MediumPostersURL = (string)x.Element("poster").Element("medium").Attribute("url"), 
          BigPostersURL = (string)x.Element("poster").Element("big").Attribute("url"), 
          MoviesURL = (string)x.Element("url"), 
          IMDB_Rating = (float)x.Element("imdb").Attribute("rating"), 
          IMDB_Votes = (float)x.Element("imdb").Attribute("votes") 
         }); 
+0

非常感謝。您的帖子非常有幫助。我添加了一點方法,現在一切都很好。我可以將SmallPostersURL =(string)x.Element(「poster」)。Element(「small」)。屬性(「url」)替換爲SmallPostersURL = TestClass.TryGetElementValue (x,「poster \\ small」,「url」 ) – Mixim