代码之家  ›  专栏  ›  技术社区  ›  core

LINQ到XML:应用XPath

  •  11
  • core  · 技术社区  · 16 年前

    有人能告诉我为什么这个程序不枚举任何项目吗?它是否与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();
        }
    }
    
    1 回复  |  直到 16 年前
        1
  •  16
  •   Jon Skeet    16 年前

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