简体   繁体   English

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

[英]c# Linq to xml - Extract parents of child element

I have this 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>

I need to extract the the parents of the Child2 where Child2Key == "TakeMe".我需要提取Child2的父母,其中Child2Key ==“TakeMe”。 The result would be:结果将是:

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

I can probably do it in 2 steps.我大概可以分两步完成。 Iterate through parent upwards from Child2 and get their keys, and in the next step remove the elements with other keys.从 Child2 向上遍历 parent 并获取它们的键,并在下一步中删除具有其他键的元素。 I'd rather do it in one query if possible.如果可能,我宁愿在一个查询中进行。

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();

First query removes all Child2 nodes which does not match search condition.第一个查询删除所有与搜索条件不匹配的Child2节点。

Second query removes all ChildL1 which do not have Child2 nodes anymore.第二个查询删除所有ChildL1不具有Child2节点了。

Special for LB 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM