的LINQ to XML查询的同级元素 [英] LINQ to XML querying for sibling elements
问题描述
很抱歉,如果这个问题是非常基本的,但我还没有与XML非常多,这是我第一次使用LINQ合作,XML ...
Sorry if this question is very basic, but I haven't worked with XML very much, and this is my first time working with LINQ to XML...
我有一个结构类似于一个目录树一个XML站点地图:
I have an XML sitemap that is structured like a directory tree:
<Site>
<File GUID="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx">FileName</file>
<Folder name="FolderName">
<Security>
<Role>Admin</role>
</Security>
<File GUID="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx">FileName</file>
<Folder name="subFoler">
<File GUID="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx">FileName</file>
<File GUID="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx">FileName</file>
<Folder>
<File GUID="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx">FileName</file>
</Folder>
</Folder>
</Folder>
</Site>
在这种方式,每个文件将继承的安全性,从它的父文件夹(或祖父母文件夹,等等,这取决于有多少了树&LT;安全&GT;&LT; /安全&GT;
的位置。
In this way, every file will inherit security from its parent folder (or grandparent folder, etc, depending upon how far up the tree the <security></security>
is located.
我希望能给出一个文件的GUID,选择使用LINQ该文件,并收集所有与该文件继承了安全相关的职务。
I want to be able to, given a file's GUID, select that file with LINQ, and gather all of the roles associated with the security that file has inherited.
这是我迄今为止,但它是一个非常粗略的尝试,是不完整的:
This is what I have so far, but it is a very rough attempt, and is not complete:
XDocument sitemap = XDocument.Load(@"\sitemap.xml");
XElement currentFile = new XElement("File",
from file in sitemap.Elements("File")
where file.Element("GUID").Equals(guid)
select file.Parent.Element("security").Elements("role"));
PS。站点地图文件位于同一目录中,该code被写入在类中
ps. The sitemap file is located within the same directory as the class in which this code is written
推荐答案
看起来要走上文件夹祖先链和积累的角色找到前进的道路上。你可以做到这一点与贴切的名字祖先()和<一HREF =http://msdn.microsoft.com/en-us/library/bb534336.aspx相对=nofollow>的SelectMany()方法:
It looks like you want to walk up the folder ancestor chain and accumulate the roles you find along the way. You can do that with the aptly-named Ancestors() and SelectMany() methods:
XElement fileFromMap = sitemap.Descendants("File").Where(
file => file.Attribute("GUID").Value == guid.ToString("D")).Single();
XElement currentFile = new XElement("File",
fileFromMap.Value,
fileFromMap.Ancestors("Folder").SelectMany(
folder => {
XElement security = folder.Element("Security");
return (security != null
? security.Elements("Role") : new XElement[0]);
}));
编辑:更改元素资本,以配合更新的问题
Changed element capitalization to match the updated question.
编辑2:的code以上被误喂空
项目的SelectMany()
(比 XElement.Add()
在这方面),而这个的导致 NullPointerException异常
。它已被更新,以返回一个空的XElement
阵列代替。
EDIT 2: The code above was mistakenly feeding a null
item to SelectMany()
(which is far less indulgent than XElement.Add()
in this regard), and this resulted in a NullPointerException
. It has been updated to return an empty XElement
array instead.
这篇关于的LINQ to XML查询的同级元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!