首页 > 解决方案 > 通过 LinqQuery 获取对象

问题描述

我有这个 XML 代码,我想过滤掉特定机构中的人员。

</persons>
     <person>
    <name>
      <fn>Donald Duck</fn>
      <n>
        <family>Duck</family>
        <given>Donald</given>
      </n>
    </name>
    <email />
    <tel teltype="voice" />
    <tel teltype="mobile" />
    <adr>
    </adr>
    <institutionrole roletype="Employee" />
    <extension>
      <institutions>
        <institution institution="Division1">
        </institution>
    <institution institution="Division2">
        </institution>
      </institutions>
    </extension>
  </person>
</persons>

我想要机构 Division2 中的所有人员。

使用此代码,我可以获得所有员工,但未按机构过滤。

    var users = (from person in xmlDoc.Descendants("person")
where (person.Element("institutionrole").Attribute("roletype").Value.ToLower() == "employee"

标签: xmllinq

解决方案


您可以使用以下内容根据嵌套元素进行过滤;这将过滤角色类型为“员工”的人员,以及他们是否属于给定机构。

var users = from person in xmlDoc.Descendants("person")
                    where person.Element("institutionrole").Attribute("roletype").Value.ToLower() == "employee"
                    && person.Descendants("institutions").Elements("institution").Attributes("institution").Where(ins=>ins.Value.ToLower() == "division2").Any()
                    select person;

推荐阅读