繁体   English   中英

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

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

我有这个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>

我大概可以分两步完成。 从 Child2 向上遍历 parent 并获取它们的键,并在下一步中删除具有其他键的元素。 如果可能,我宁愿在一个查询中进行。

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

暂无
暂无

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

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