c# - 使用 LINQ to XML 处理多个命名空间中的 XML

标签 c# xml linq-to-xml

我正在尝试解析来自 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/

相关文章:

c# - 使用动态 Linq 查询子字符串时出错

c# - Linq To Entities Group By 键中有多个表

c# - 通过以字符串开头的属性在xml中查找节点

xml - Groovy Xml Holder 返回 'null' 作为现有属性的值

c# - 如何使用 C# 从 XElement 获取元素名称?

c# - 如何使用数组项的父节点从 JSON 生成 XML

c# - linq 如何选择具有包含一个或多个值数组(或列表)的子集合的父项

c# - 使用 C#(日期)和 DateTimePicker 格式化 MySQL 数据

java - 将 FXML 与 "pure javafx"代码混合

c# - Linq to XML 获取一对多元素名称和属性名称/值