Search code examples
c#.netxmlxpathxslt

XElement.XPathSelectElements returns no matching elements


I'm having some trouble getting the extension methods in System.Xml.XPath to work for me. I'm using .NET 4.5 and VS 2012.

I've included a basic example of what I'm trying to do below (i.e. use the extension methods to use XPath to select XML-nodes). Expected results were sanity-checked using http://www.xpathtester.com/.

For each case, I get 0 elements returned. What am I doing wrong?

class Program
{
    static void Main(string[] args)
    {
        XElement root = XElement.Parse("<a><b /><b /><b><c id='1'/><c id='2' /></b></a>");
        ReportMatchingNodeCount(root, "/a"); // I would expect 1 match
        ReportMatchingNodeCount(root, "/a/b"); // I would expect 3 matches
        ReportMatchingNodeCount(root, "/a/b/c"); // I would expect 2 matches
        ReportMatchingNodeCount(root, "/a/b/c[@id='1']"); // I would expect 1 match
        ReportMatchingNodeCount(root, "/a/b/c[@id='2']"); // I would expect 1 match
        Console.ReadLine();
    }

    private static void ReportMatchingNodeCount(XElement root, string xpath)
    {
        int matches = root.XPathSelectElements(xpath).Count();
        Console.WriteLine(matches);
    }
}

Solution

  • a is the root element so your XPath is looking for /a/a/b

    Try:

    ReportMatchingNodeCount(root, "/b"); // I would expect 3 matches
    ReportMatchingNodeCount(root, "/b/c"); // I would expect 2 matches
    ReportMatchingNodeCount(root, "/b/c[@id='1']"); // I would expect 1 match
    ReportMatchingNodeCount(root, "/b/c[@id='2']"); // I would expect 1 match
    

    Returns: 3 2 1 1