2014-03-25 99 views
1

鑑於來自請求的XML(用XXX取代任何用戶想要的),無法真正弄清楚爲什麼它不會返回2個測試對象到列表中,因爲它應該。Xdocument和linq - 不循環通過元素

String YouTubeXML = new WebClient().DownloadString("http://gdata.youtube.com/feeds/api/users/XXXXXXXXX/uploads?orderby=published"); 
XDocument xDoc = XDocument.Parse(YouTubeXML); 

List<dynamic> videos = (from i in xDoc.Descendants("entry") 
         select new 
         { 
          //Just declaring something random 
          Title = i.Element("id").Value 

         }).ToList<dynamic>(); 

和XML結構看起來是這樣的:

<feed xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:gd="http://schemas.google.com/g/2005" xmlns:yt="http://gdata.youtube.com/schemas/2007"> 
<id>http://gdata.youtube.com/feeds/api/users/XXXXXXXX/uploads</id> 
<author> 
    <name>XXXXXXXX</name> 
    <uri>http://gdata.youtube.com/feeds/api/users/XXXXXXXX</uri> 
</author> 
<generator version="2.1" uri="http://gdata.youtube.com">YouTube data API</generator> 
<openSearch:totalResults>5</openSearch:totalResults> 
<openSearch:startIndex>1</openSearch:startIndex> 
<openSearch:itemsPerPage>25</openSearch:itemsPerPage> 
<entry> 
    <id>http://gdata.youtube.com/feeds/api/videos/video1</id> 
    <published>date</published> 
    <updated>date</updated> 
    <author> 
    <name>name</name> 
    <uri>http://gdata.youtube.com/feeds/api/users/XXXXXXX</uri> 
    </author> 
    <yt:hd /> 
    <media:group> 
    <yt:duration seconds="179" /> 
    </media:group> 
    <gd:rating average="4.703704" max="5" min="1" numRaters="81" rel="http://schemas.google.com/g/2005#overall" /> 
    <yt:statistics favoriteCount="0" viewCount="6004" /> 
</entry> 
<entry> 
    <id>http://gdata.youtube.com/feeds/api/videos/video2</id> 
    <published>date</published> 
    <updated>date</updated> 
    <author> 
    <name>name</name> 
<uri>http://gdata.youtube.com/feeds/api/users/XXXXXXX</uri> 
    </author> 
    <yt:hd /> 
    <media:group> 
    <yt:duration seconds="179" /> 
    </media:group> 
    <gd:rating average="4.703704" max="5" min="1" numRaters="81"   rel="http://schemas.google.com/g/2005#overall" /> 
    <yt:statistics favoriteCount="0" viewCount="6004" /> 
</entry> 
</feed> 

什麼能可能會錯誤? XML正在接收和解析,因此這是查詢不起作用。

回答

1

你錯過了一個事實,即XML使用命名空間,所以你的查詢必須使用命名空間太:

var ns = XNamespace.Get("http://www.w3.org/2005/Atom"); 
var videos = (from i in xDoc.Root.Elements(ns + "entry") 
       select new 
       { 
        Title = (string)i.Element(ns + "id") 
       }).ToList(); 
+0

非常感謝。我知道我錯過了一些我根本不知道的東西。豎起大拇指! – Afonso