简体   繁体   English

LINQ to XML递归删除元素-C#

[英]LINQ to XML recursively remove elements - C#

I have the following XML: 我有以下XML:

<Root>
 <Section name="xyz" />
 <Section name="abc">
   <Section name="def" />
 </Section>
 <Section name="abc">
   <Section name="def">
     <Section name="xyz" />
     <Section name="abc" />
     <Section name="xyz">
       <Section name="xyz" />
     </Section>
  </Section>
</Section>
</Root>

I have the XDocument representation of the XML. 我有XML的XDocument表示形式。 How I do traverse through the tree and remove all elements with say abc 我如何遍历树并使用abc删除所有元素

That's really easy :) 真的很简单:)

doc.Descendants("Section")
   .Where(x => (string) x.Attribute("name") == "xyz")
   .Remove();

Gotta love LINQ to XML... 一定喜欢LINQ to XML ...

EDIT: I've just tried it with your sample XML, and this was the result afterwards: 编辑:我刚刚用您的示例XML尝试过,这是之后的结果:

<Root>
  <Section name="abc">
    <Section name="def" />
  </Section>
  <Section name="abc">
    <Section name="def">
      <Section name="abc" />
    </Section>
  </Section>
</Root>

Please let me know if that's not what you were expecting. 如果那不是您所期望的,请告诉我。

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

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