c#Linq to xml - 提取子元素的父元素

时间:2012-11-10 22:17:54

标签: c# linq-to-xml

我有这个xml:

<Root>
  <RootKey>1</RootKey>
  <ChildL1>
    <ChildL1Key>12</ChildL1Key>
    <Child2>
      <Child2Key>TakeMe</Child2Key>
    </Child2>
    <Child2>
      <Child2Key>365</Child2Key>
    </Child2>
  </ChildL1>
  <ChildL1>
    <ChildL1Key>95</ChildL1Key>
    <Child2>
      <Child2Key>958</Child2Key>
    </Child2>
    <Child2>
      <Child2Key>574</Child2Key>
    </Child2>
  </ChildL1>
</Root>

我需要提取 Child2 的父母,其中 Child2Key ==“TakeMe”。结果将是:

<Root>
  <RootKey>1</RootKey>
  <ChildL1>
    <ChildL1Key>12</ChildL1Key>
    <Child2>
      <Child2Key>TakeMe</Child2Key>
    </Child2>
  </ChildL1>
</Root>

我可以分2步完成。从Child2向上遍历父项并获取其键,然后在下一步中使用其他键删除元素。如果可能的话,我宁愿在一个查询中这样做。

1 个答案:

答案 0 :(得分:0)

XDocument xdoc = XDocument.Load(path_to_xml);
xdoc.Descendants("Child2")
    .Where(c2 => c2.Element("Child2Key").Value != "TakeMe")
    .Remove();

xdoc.Descendants("ChildL1")
    .Where(c1 => !c1.Descendants("Child2").Any())
    .Remove();

// now xdoc contains what you need
string xml = xdoc.ToString();

第一个查询删除与搜索条件不匹配的所有Child2个节点。

第二个查询将删除所有没有ChildL1个节点的Child2

LB特别

xdoc.Descendants("ChildL1")            
    .Where(c1 => !c1.Descendants("Child2")
                    .Any(c2 => c2.Element("Child2Key").Value == "TakeMe"))
    .Concat(xdoc.Descendants("Child2")
                .Where(c2 => c2.Element("Child2Key").Value != "TakeMe"))
    .Remove();