简体   繁体   中英

c# Linq to xml - Extract parents of child element

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

Second query removes all ChildL1 which do not have Child2 nodes anymore.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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