使用LINQ to XML处理多个命名空间中的XML [英] Using LINQ to XML to Process XML in Multiple Namespaces
问题描述
我正在尝试解析YouTube API的结果.我以字符串形式正确获取结果,但是无法正确解析它.
I'm trying to parse results from the YouTube API. I'm getting the results correctly as a string, but am unable to parse it correctly.
我遵循了上一个线程的建议,但没有得到任何结果.
I followed suggestions on a previous thread, but am not getting any results.
我的示例代码是:
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
}
问题在于,即使XDocument显然具有有效值,条目的计数也为0.
The problem is that entries has a count of 0 even though the XDocument clearly has the valid values.
可以在此处看到响应变量(示例XML)的值: http://snipt.org/lWm
The value of the response variable (Sample XML) can be seen here: http://snipt.org/lWm
(仅供参考:此处列出了youTube架构: http://code .google.com/apis/youtube/2.0/developers_guide_protocol_understanding_video_feeds.html )
(FYI: The youTube schema is listed here: http://code.google.com/apis/youtube/2.0/developers_guide_protocol_understanding_video_feeds.html)
有人可以告诉我我在做什么错吗?
Can anyone tell me what I'm doing wrong here?
推荐答案
所有数据都位于" http://www.w3.org/2005/Atom 名称空间;您需要在整个过程中使用它:
All the data is in the "http://www.w3.org/2005/Atom" namespace; you need to use this throughout:
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)
...
};
等(未试用)
这篇关于使用LINQ to XML处理多个命名空间中的XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!