Linq to XML,仅获取具有特定子元素的元素
我想向老歌(但好歌)问一个后续问题 从 csproj 文件中读取引用列表(尽管我不是该问题的作者)。
在解析 csproj 文件时,我需要选择所有将 Link 元素作为子元素的 Compile 元素。
我首先尝试将链接问题的答案扩展如下:
IEnumerable<string> links = csprojFile
Element(msbuild + "Project")
.Elements(msbuild + "ItemGroup")
.Elements(msbuild + "Compile")
.Where(element => element.HasElements)
.Attributes("Include")
这显然是不够的,因为它会选择具有任何类型子级的所有元素(因此,在选择我想要的元素时,它还会选择额外的元素)。然后我尝试:
IEnumerable<string> links = csprojFile
.Element(msbuild + "Project")
.Elements(msbuild + "ItemGroup")
.Elements(msbuild + "Compile")
.Where(element => element.HasElements && element.Descendants("Link").Any())
.Attributes("Include")
.Select(element => element.Value);
...它不会返回任何内容。我是 Linq 的初学者,特别是 Linq2XML 的初学者,但对我来说,“Where”子句说:“where 元素有子元素,并且这些子元素中至少有一个名为 Link”。这是错误的吗?
非常感谢您的帮助。
I would like to ask a follow up question to an oldie (but goodie) Reading the list of References from csproj files (though I am not the author of that question).
In my parsing of the csproj files I need to select all Compile elements that have Link element as a child.
I first attempted to extend the answer to the linked question as follows:
IEnumerable<string> links = csprojFile
Element(msbuild + "Project")
.Elements(msbuild + "ItemGroup")
.Elements(msbuild + "Compile")
.Where(element => element.HasElements)
.Attributes("Include")
Which is obviously insufficient since it picks all elements that have any type of children (so while picking the ones I want, it also picks extras). So then I tried:
IEnumerable<string> links = csprojFile
.Element(msbuild + "Project")
.Elements(msbuild + "ItemGroup")
.Elements(msbuild + "Compile")
.Where(element => element.HasElements && element.Descendants("Link").Any())
.Attributes("Include")
.Select(element => element.Value);
... which doesn't return anything. I'm a beginner in Linq in general and Linq2XML in particular, but to me that "Where" clause says: "where element has children and at least one of those children is named Link". Is that wrong?
Help is greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我怀疑这是一个命名空间问题 - 您没有使用“链接”的命名空间。试试这个:
(HasElements 并不是真正必要的。)
I suspect it's a namespace problem - you're not using the namespace for "Link". Try this:
(The HasElements isn't really necessary.)