I want to remove an element from an XML Tree and I tried using the method mentioned in the following URL to do that.
https://msdn.microsoft.com/en-us/library/bb387051.aspx
My XML is kinda different from the above and when I tried to use this it only removes the Grandchild1 in the first node. It doesn't do it for the second one.
XElement root = XElement.Parse(@"<Root>
<Child1>
<GrandChild1/>
<GrandChild2/>
<GrandChild3/>
</Child1>
<Child1>
<GrandChild1/>
<GrandChild2/>
<GrandChild3/>
</Child1>
</Root>");
root.Element("Child1").Element("GrandChild1").Remove();
output after executing:
<Child1>
<GrandChild2/>
<GrandChild3/>
</Child1>
<Child1>
<GrandChild1/>
<GrandChild2/>
<GrandChild3/>
</Child1>
expected output:
<Child1>
<GrandChild2/>
<GrandChild3/>
</Child1>
<Child1>
<GrandChild2/>
<GrandChild3/>
</Child1>
Why doesn't it do it and how can I make it work?
Thanks!
The Element
method only returns a single element. You want:
root.Elements("Child1").Elements("GrandChild1").Remove();
That uses:
XContainer.Elements
methodExtensions.Elements
extension method (on IEnumerable<T> where T : XContainer
)Extensions.Remove
extension method (on IEnumerable<T> where T : XNode
)So that will find every GrandChild1
element directly under a Child1
element directly under the root. If you actually don't care where the GrandChild1
element is found, you an use
root.Descendants("GrandChild1").Remove();
... but using Elements
gives you a bit more control.
See more on this question at Stackoverflow