我正在尝试解析来自 YouTube API 的结果。我以字符串形式正确获取结果,但无法正确解析它。
我遵循了上一个线程中的建议,但没有得到任何结果。
我的示例代码是:
string response = youtubeService.GetSearchResults(search.Term, "published", 1, 50);
XDocument xDoc = XDocument.Parse(response, LoadOptions.SetLineInfo);
var list = xDoc.Descendants("entry").ToList();
var entries = from entry in xDoc.Descendants("entry")
select new
{
Id = entry.Element("id").Value,
Categories = entry.Elements("category").Select(c => c.Value)
//Published = entry.Element("published").Value,
//Title = entry.Element("title").Value,
//AuthorName = entry.Element("author").Element("name").Value,
//Thumnail = entry.Element("media:group").Elements("media:thumnail").ToList().ElementAt(0)
};
foreach (var entry in entries)
{
// entry.Id and entry.Categories available here
}
问题是条目的计数为 0,即使 XDocument 显然具有有效值。
可在此处查看响应变量的值(示例 XML):http://snipt.org/lWm
(仅供引用:此处列出了 YouTube 架构:http://code.google.com/apis/youtube/2.0/developers_guide_protocol_understanding_video_feeds.html)
谁能告诉我我做错了什么?
最佳答案
所有数据都在“http://www.w3.org/2005/Atom”命名空间中;你需要在整个过程中使用它:
XNamespace ns = XNamespace.Get("http://www.w3.org/2005/Atom");
...
from entry in xDoc.Descendants(ns + "entry")
select new
{
Id = entry.Element(ns + "id").Value,
Categories = entry.Elements(ns + "category").Select(c => c.Value)
...
};
等(未经测试)
关于c# - 使用 LINQ to XML 处理多个命名空间中的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1224896/