无法选择相关的嵌套节点:LINQ

时间:2013-09-20 07:07:57

标签: c# linq

我的示例XML是这样的:

<?xml version="1.0" encoding="utf-8"?>
<Root>
  <RoleSecurity Name="A" Workflowstatus ="B">
    <Accountgroup Name = "Group1">
      <Attribute ID="12345" Name="Sample1"/>
      <Attribute ID="12445" Name="Sample2"/>
    </Accountgroup>
    <Accountgroup Name = "Group2">
      <Attribute ID="12345" Name="Sample1"/>
      <Attribute ID="12445" Name="Sample2"/>
    </Accountgroup>
  </RoleSecurity>
</Root>

我正在尝试枚举并提取与特定角色名称,工作流程状态和帐户组对应的所有ID。

我的LINQ查询正在根据角色名称选择节点。但我无法继续前进。 请帮忙!

到目前为止,这是我的LINQ代码。

XElement xcd = XElement.Load(strFileName);
IEnumerable<XElement> enumCust = from cust in xcd.Elements("RoleSecurity")
           where (string)cust.Attribute("Name") == strRole
           select cust;

4 个答案:

答案 0 :(得分:1)

试试这个:

string roleName = "A";
string workflowStatus = "B";
string accountGroup = "Group1";

string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
    <Root>
        <RoleSecurity Name=""A"" Workflowstatus =""B"">
        <Accountgroup Name = ""Group1"">
            <Attribute ID=""12345"" Name=""Sample1""/>
            <Attribute ID=""12445"" Name=""Sample2""/>
        </Accountgroup>
        <Accountgroup Name = ""Group2"">
            <Attribute ID=""12345"" Name=""Sample1""/>
            <Attribute ID=""12445"" Name=""Sample2""/>
        </Accountgroup>
        </RoleSecurity>
    </Root>";

XElement element = XElement.Parse(xml);

var ids = element.Elements("RoleSecurity")
    .Where(
        e =>
            (string) e.Attribute("Name") == roleName &&
            (string) e.Attribute("Workflowstatus") == workflowStatus)
    .Elements("Accountgroup").Where(e => (string) e.Attribute("Name") == accountGroup)
    .Elements("Attribute")
    .Select(e => new {ID = (string) e.Attribute("ID"), Name = (string) e.Attribute("Name")});

答案 1 :(得分:1)

尝试使用这种方法,看起来与您的不同(在某些方面它确实发生了变化),但在我看来,它是一种流畅地使用LINQ查询来解析XML文件的好方法,它遵循XML节点序列并且很容易理解:

  XElement element = XElement.Load(strFileName);

  var linqList = element.Elements("RoleSecurity")
                              .Where(entry => entry.Attribute("Name").Value == "A" && 
                               entry.Attribute("Workflowstatus").Value == "B")
                                  .Descendants("Accountgroup")
                                  .Where(x => x.Attribute("Name").Value == "Group1")
                                     .Descendants("Attribute")
                                     .SelectMany(id => id.Attribute("ID").Value);

答案 2 :(得分:0)

XElement xcd = XElement.Load(strFileName);
IEnumerable<XElement> enumCust = from cust in xcd.Root.Elements("RoleSecurity")
           where cust.Attribute("Name").Value == strRole
           select cust;

现在应该可以了 你错过了.Root,这是在根节点下面枚举所必需的 和.Value来检索指定属性的字符串值

答案 3 :(得分:0)

<首选此文章: - http://www.dotnetcurry.com/ShowArticle.aspx?ID=564

foreach (XElement xcd xelement.Descendants("Id"))
    {
        Console.WriteLine((string)xcd);
    }