c# - LINQ 到 XML : applying an XPath

标签 c# xml linq xpath linq-to-xml

有人能告诉我为什么这个程序不枚举任何项目吗?它与 RDF namespace 有关吗?

using System;
using System.Xml.Linq;
using System.Xml.XPath;

class Program
{
    static void Main(string[] args)
    {
        var doc = XDocument.Load("http://seattle.craigslist.org/sof/index.rss");

        foreach (var item in doc.XPathSelectElements("//item"))
        {
            Console.WriteLine(item.Element("link").Value);
        }

        Console.Read();
    }
}

最佳答案

是的,它绝对是关于命名空间的——尽管它是 RSS 命名空间,而不是 RDF 命名空间。您正在尝试查找没有 namespace 的项目。

在 .NET 的 XPath 中使用命名空间有点棘手,但在这种情况下,我只使用 LINQ to XML Descendants 方法:

using System;
using System.Linq;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        var doc = XDocument.Load("http://seattle.craigslist.org/sof/index.rss");
        XNamespace rss = "http://purl.org/rss/1.0/";

        foreach (var item in doc.Descendants(rss + "item"))
        {
            Console.WriteLine(item.Element(rss + "link").Value);
        }

        Console.Read();
    }
}

关于c# - LINQ 到 XML : applying an XPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1583086/

相关文章:

c# - linq lambda多步骤数组

c# - 从 SQL Server 数据库更新前端 WPF 应用程序

c# - 如何调用Action<>修改winforms控件

c# - 将两个字符串合并为 DateTime

javascript - 我似乎无法在 JS 中正确解析 XML 数据

非 XML 中的 C# 文档

c# - LINQ to Entities 中的批量删除

c# - 如何在 C# 中调整图像大小同时保持高质量?

javascript - 无法在 MVC 中捆绑 jQuery 文件

html - 如何解析 HTML 以搜索特定内容的针