考虑到请求中的xml(XXX被用户想要的替换),不能确定为什么它不会将2个测试对象返回到列表中。
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,因此查询无法正常工作。
答案 0 :(得分: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();