XElement.XPathSelectElements不返回匹配的元素

时间:2013-11-24 22:47:06

标签: c# xml xpath

我在System.Xml.XPath中使用扩展方法为我工作时遇到了一些麻烦。我正在使用.NET 4.5和VS 2012。

我已经包含了我在下面尝试做的基本示例(即使用扩展方法来使用XPath来选择XML节点)。使用http://www.xpathtester.com/对预期结果进行了健全性检查。

对于每种情况,我都会返回0个元素。我做错了什么?

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

3 个答案:

答案 0 :(得分:1)

我从每个查询中删除前导斜杠(/)。您可能还需要在XML的开头添加XML声明。见下文:

<?xml version="1.0" encoding="UTF-8"?>

答案 1 :(得分:1)

这是因为XElement.Parsea元素作为当前节点返回。请改用XDocument.Parse

使用此代码,它提供了预期的结果。

static void Main(string[] args)
{
    var root = XDocument.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(XNode root, string xpath)
{
    int matches = root.XPathSelectElements(xpath).Count();
    Console.WriteLine(matches);
}

答案 2 :(得分:1)

a是根元素,因此您的XPath正在寻找/a/a/b

尝试:

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

返回:3 2 1 1