1

我有 XElement x

<projects><project><id>2</id><name>Project A</name></project>
<project><id>7</id><name>Blue-Leafed Project B</name></project></projects>

比我使用 XPathSelectElements 并期望获得 2 个节点:

var projects = x.XPathSelectElements("/projects/project");

result = null;

我也试图稍微改变 XPath

result = null;

这有什么问题?

4

2 回答 2

1

What is most likely happened is that you loaded your document as an XElement and therefore x is already referring to the root node projects. Your queries have to be relative to that node and that node clearly doesn't have a projects child. You're trying to select the child project elements relative to your projects node so your query should be:

var projects = x.XPathSelectElements("project");

Though in this case, you don't really need to use xpath, just use the Elements() method instead.

var projects = x.Elements("project");

You generally should use XDocument objects to load the document instead of XElement, otherwise you'd run into these kinds of problems.

于 2013-05-27T09:13:16.390 回答
0

你可以试试这个:

var projects = x.XPathSelectElements("./projects/project");
于 2013-05-27T09:05:36.567 回答