根据属性值分组递归子元素



下面是我的示例XML。我如何使用LINQ到XML对这些Department元素进行分组,其中每个元素都具有属性hasLab='1' ?

   <ResearchLabs>
  <Departments>
    <Department  hasLab="1">
      <Department hasLab="0">
        <Subject name="Pharma"/>
        <Department hasLab="1">
          <Department hasLab="0">
            <Subject name="Data"/>
          </Department>
        </Department>
      </Department>
      <Department hasLab="0">
        <Subject name="Submission"/>
      </Department>
    </Department>
  </Departments>
</ResearchLabs>

这是你要找的吗?

这将所有没有实验室的子部门分组到有实验室的父部门。

var query = from dept in doc.Descendants("Department")
            where (int)dept.Attribute("hasLab") == 0
               && dept.Parent.Name == "Department" // probably not needed
               && (int)dept.Parent.Attribute("hasLab") == 1
            group dept by dept.Parent;

或者另一个查询,可能更有效:

var query = from dept in doc.Descendants("Department")
            where (int)dept.Attribute("hasLab") == 1
            from sub in dept.Elements("Department")
            where (int)sub.Attribute("hasLab") == 0
            group sub by dept;

虽然我不喜欢创建分组(绝对更有效率):

var query = from dept in doc.Descendants("Department")
            where (int)dept.Attribute("hasLab") == 1
            select new
            {
                Parent   = dept,
                Children = dept.Elements("Department")
                               .Where(sub => (int)sub.Attribute("hasLab") == 0),
            };

不清楚您要做什么,但您可以使用:

var grouped = xml.Descendants("Department")
                 .GroupBy(x => (int) x.Attribute("hasLab"));

相关内容

  • 没有找到相关文章

最新更新