有人能告诉我为什么这个程序不枚举任何项目吗?它与 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/