【问题标题】:LINQ to XML: applying an XPathLINQ to XML:应用 XPath
【发布时间】:2009-10-17 20:06:31
【问题描述】:

谁能告诉我为什么这个程序不枚举任何项目?和 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();
    }
}

【问题讨论】:

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


    【解决方案1】:

    是的,这绝对是关于名称空间的——尽管它是 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();
        }
    }
    

    【讨论】:

    • 赢家,鸡肉晚餐。
    • 在 C# 中解析 RDF、RSS 和 ATOM 的完整示例可以在这里找到 jarloo.com/rumormill-5 也可以找到完整的源代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多