通过 XDocument.Descendants 的 C#.NET XML 处理未按预期获取实体

发布于 2024-12-27 05:15:13 字数 1630 浏览 3 评论 0原文

使用 XDocument后代方法。

//first problem 'entries' doesn't fetch at all
var entries = xmlDoc.Descendants(XName.Get("entry"))
//neither does
//            xmlDoc.Descendants("entry")

var ids = from e in entries 
          select e.Element(XName.Get("id")).Value;

相同的 XDocument 代码适用于更详细的博客提要,即我的博客: http://blog.nick .josevski.com/feed/ 一个片段在这里:http://pastebin.com/KU65dgwL,其中“entry”元素替换为“item”,“id”替换为“link”。

为了测试任何建议,我创建了一个 LinqPad 代码要点来演示该问题。

我错过了一些明显的东西吗?我尝试了 .Elements() .Elements("entry").Descendants() 的各种组合,然后尝试过滤进一步也没有运气。

这是我正在努力从中提取条目/id 节点的 XML:

<feed xmlns="http://www.w3.org/2005/Atom">
    <title type="text">Author</title>
    <subtitle type="text">subtitle</subtitle>
    <link rel="alternate" href="http://www.site.com/blog" />
    <entry>
        <id>http://www.site.com/a-blog-post</id>
        <title type="text">Title Of Blog Post</title>

    ...

    <entry>
        <id>http://www.site.com/another-blog-post</id>
        <title type="text">Title Of Another Blog Post</title>

Using an XDocument and the Descendants method.

//first problem 'entries' doesn't fetch at all
var entries = xmlDoc.Descendants(XName.Get("entry"))
//neither does
//            xmlDoc.Descendants("entry")

var ids = from e in entries 
          select e.Element(XName.Get("id")).Value;

The same XDocument code works on a blog feed that's more verbose, i.e. my blog: http://blog.nick.josevski.com/feed/ a snippet is here: http://pastebin.com/KU65dgwL where the 'entry' element is replaced with 'item' and 'id' is replaced with 'link'.

To test any suggestions I created a LinqPad code gist that demonstrates the issue.

Am I missing something obvious? I've tried various combinations of .Elements() .Elements("entry") and just .Descendants() and then attempting to filter further without luck too.

This is the XML that I'm struggling to extract the entry/id node from:

<feed xmlns="http://www.w3.org/2005/Atom">
    <title type="text">Author</title>
    <subtitle type="text">subtitle</subtitle>
    <link rel="alternate" href="http://www.site.com/blog" />
    <entry>
        <id>http://www.site.com/a-blog-post</id>
        <title type="text">Title Of Blog Post</title>

    ...

    <entry>
        <id>http://www.site.com/another-blog-post</id>
        <title type="text">Title Of Another Blog Post</title>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟若柳尘 2025-01-03 05:15:13

您缺少 XML 命名空间:

XNamespace ns = "http://www.w3.org/2005/Atom";
var entries = xmlDoc.Descendants(ns + "entry");

You are missing the XML namespace:

XNamespace ns = "http://www.w3.org/2005/Atom";
var entries = xmlDoc.Descendants(ns + "entry");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文