LINQ到XML:将一个XPath [英] LINQ to XML: applying an XPath

查看:151
本文介绍了LINQ到XML:将一个XPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我为什么这个程序不枚举任何项目? ?它有什么做的RDF命名空间

 使用系统; 
使用System.Xml.Linq的;
使用System.Xml.XPath;

类节目
{
静态无效的主要(字串[] args)
{
VAR DOC = XDocument.Load(HTTP://西雅图.craigslist.org / SOF / index.rss);

的foreach(在doc.XPathSelectElements VAR项目(//项目))
{
Console.WriteLine(item.Element(链接)值。);
}

Console.Read();
}
}


解决方案

是的,这是绝对有关的命名空间 - 尽管它是RSS的命名空间,而不是RDF之一。你想找到没有命名空间的项目。



在.NET中的XPath使用一个命名空间稍微靠谱,但在这种情况下,我只使用LINQ到XML 后裔方法,而不是:

 使用系统; 
使用System.Linq的;
使用System.Xml.Linq的;

类测试
{
静态无效的主要()
{
VAR DOC = XDocument.Load(http://seattle.craigslist.org /sof/index.rss);
的XNamespace RSS =htt​​p://purl.org/rss/1.0/;

的foreach(在doc.Descendants VAR项(RSS +项目))
{
Console.WriteLine(item.Element(RSS +链接)。值) ;
}

Console.Read();
}
}


Can someone tell me why this program doesn't enumerate any items? Does it have something to do with the 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();
    }
}

解决方案

Yes, it's absolutely about the namespace - although it's the RSS namespace, not the RDF one. You're trying to find items without a namespace.

Using a namespace in XPath in .NET is slightly tricky, but in this case I'd just use the LINQ to XML Descendants method instead:

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

这篇关于LINQ到XML:将一个XPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆