C# 使用XPath返回具有特定属性的所有元素
因此,我在C# 使用XPath返回具有特定属性的所有元素,c#,xml,xpath,C#,Xml,Xpath,因此,我在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">
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>
但是它返回的是完整文档中的所有元素,而不是我试图查询的currentXElement
部分
我能做什么?我也尝试过使用/item[@link]
,但没有返回任何内容
谢谢
编辑:
最后,正如谢尔盖所说
return currentXElement.Descendants("item").Where(i => i.Attribute("link") != null).Select(item => new IpjItem(item));
//item
表达式选择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)
您需要使用XPath有什么原因吗?您已经完全准备好只使用LINQ了吗?您可以提供复制您的问题的示例xml吗?@Jonesy首先我认为使用
LINQ
,但我认为XPath返回所有链接更有效。您将如何使用Linq?问题是我有太多的子体,它们也可能包含链接。@SergeyBerezovskiy,基本上,完整的文档只是一个巨大的文件,其中包含名为items的元素。所以,想象一下之前和之后的项目。如果我不知道完整路径怎么办?我可以在C,D。。。有没有选择属性的通用方法?太棒了。谢谢,谢尔盖
currentXElement.Descendants("item").Where(i => i.Attribute("link") != null)