簡體   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