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

本文关键字:属性 元素 XPath 返回 使用 | 更新日期: 2023-09-27 18:19:05

那么,我在Xml文件中有一个XElement,看起来像这样:

... 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>

现在,我想使用XPath

返回只包含属性link的元素的IEnumerable<Element>对象

在我的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));

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

//item表达式选择条目元素,无论它们在文档中的位置。如果要选择相对于当前元素的项,则应该使用完整路径。例如

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)