问题 LINQ to XML:应用XPath


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

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();
    }
}

2456
2017-10-17 20:06


起源



答案:


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

在.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();
    }
}

16
2017-10-17 20:09



获奖者,鸡肉晚餐。 - core
可以在此处找到在C#中解析RDF,RSS和ATOM的完整示例 jarloo.com/rumormill-5 也提供完整的源代码。 - Kelly


答案:


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

在.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();
    }
}

16
2017-10-17 20:09



获奖者,鸡肉晚餐。 - core
可以在此处找到在C#中解析RDF,RSS和ATOM的完整示例 jarloo.com/rumormill-5 也提供完整的源代码。 - Kelly