使用XPath返回具有特定属性的所有元素

时间:2014-08-22 19:55:45

标签: c# xml xpath

所以,我在XElement文件中有Xml,看起来像这样:

... More parent nodes  
<item cid="0x14c8" name="A" id="0xaf4b6f8">
    <item cid="0x57c" luid="2001"/>
    <item cid="0x578" luid="2000" value="0"/>

    <item cid="0x14fa" name="B">
            <item cid="0x57a" luid="2024" value="1.00"/>
            <item cid="0x579" luid="2025" value="0"/>
            <item link="0xb199640" cid="0x474" luid="5372"/>
            ...More descendants
    </item>

现在,我想使用IEnumerable<Element>

返回仅包含属性link的元素的XPath个对象

在我的query中,我正在做:

return currentXElement.XPathSelectElements("//item[@link]").Select(item => new Element(item));

但它会返回完整文档中的所有元素,而不是currentXElement,这是我尝试查询的部分。

我该怎么办?我也试过使用/item[@link],但没有返回任何内容。

由于

修改

最后,正如谢尔盖所​​说,

return currentXElement.Descendants("item").Where(i => i.Attribute("link") != null).Select(item => new IpjItem(item));

1 个答案:

答案 0 :(得分:1)

//item表达式选择项目元素,无论它们在文档中的位置。如果要选择与当前元素相关的项,则应使用完整路径。 E.g。

xdoc.Root.XPathSelectElements("//item[@name='B']//item[@link]")

这里我假设//item[@name='B']选择你的currentElement(你应该使用选择你当前元素的表达式),然后用//item[@link]你正在搜索相对于名字的项目的后代项目B

注意:我认为纯LINQ在这里会更好

currentXElement.Descendants("item").Where(i => i.Attribute("link") != null)
相关问题