加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – LINQ to XML:应用XPath

发布时间:2020-12-15 06:39:17 所属栏目:百科 来源:网络整理
导读:有人可以告诉我为什么这个程序不列举任何项目?它与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/inde
有人可以告诉我为什么这个程序不列举任何项目?它与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();
    }
}

解决方法

是的,它绝对是命名空间 – 尽管它是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();
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读