Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to XML: applying an XPath

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();
    }
}
like image 435
core Avatar asked Oct 17 '09 20:10

core


1 Answers

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();
    }
}
like image 77
Jon Skeet Avatar answered Nov 11 '22 07:11

Jon Skeet