选择XMLDocument中具有特定名称和唯一属性的所有节点

时间:2017-01-31 16:04:59

标签: c# unique nodes xmldocument

我有以下XML文件:

<RightsSetup>
  <Group Name="Sachbearbeiter">
    <List Url="Lists/List1">
      <RoleDefinition ID="3" />
    </List>
    <List Url="Lists/List2">
      <RoleDefinition ID="3" />
    </List>
    <List Url="Lists/List3">
      <RoleDefinition ID="3" />
    </List>
  </Group>
  <Group Name="Administratoren">
    <List Url="Lists/List1">
      <RoleDefinition ID="3" />
    </List>
    <List Url="Lists/List2">
      <RoleDefinition ID="3" />
    </List>
    <List Url="Lists/List3">
      <RoleDefinition ID="3" />
    </List>
  </Group>
  <Group Name="Finanzverwalter">
    <List Url="Lists/List1">
      <RoleDefinition ID="0" />
    </List>
    <List Url="Lists/List2">
      <RoleDefinition ID="0" />
    </List>
    <List Url="Lists/List3">
      <RoleDefinition ID="0" />
    </List>
  </Group>
  <Group Name="Gutachter">
    <List Url="Lists/List1">
      <RoleDefinition ID="2" />
    </List>
    <List Url="Lists/List2">
      <RoleDefinition ID="2" />
    </List>
    <List Url="Lists/List3">
      <RoleDefinition ID="2" />
    </List>
  </Group>
  <Group Name="Mentoren">
    <List Url="Lists/List1">
      <RoleDefinition ID="2" />
    </List>
    <List Url="Lists/List2">
      <RoleDefinition ID="2" />
    </List>
    <List Url="Lists/List3">
      <RoleDefinition ID="2" />
    </List>
  </Group>
  <Group Name="Ausschuss">
    <List Url="Lists/List1">
      <RoleDefinition ID="2" />
    </List>
    <List Url="Lists/List2">
      <RoleDefinition ID="2" />
    </List>
    <List Url="Lists/List3">
      <RoleDefinition ID="2" />
    </List>
  </Group>
</RightsSetup>

现在我需要选择具有唯一List属性的所有URL个节点,因此我的结果只有3个节点。

我已经使用

选择了所有List个节点
this.XmlDocument.SelectNodes("//List");

但我不知道如何只选择具有唯一Url属性的节点。那我怎么能实现这个呢?

1 个答案:

答案 0 :(得分:0)

使用GROUPBY尝试xml linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

             var groups = doc.Descendants("Group").Select(x => new {
                lists = x.Elements("List").Select(y => new {
                    url = (string)y.Attribute("Url"),
                    list = y
                })
                .Select(z => new { name = (string)x.Attribute("Name"), list = z.list, url = (string)z.url})
             }).SelectMany(y => y.lists).GroupBy(x => x.url).ToList();

        }
    }
}