This documentation is archived and is not being maintained.

Removing Elements, Attributes, and Nodes from an XML Tree

You can modify an XML tree, removing elements, attributes, and other types of nodes.

Removing a single element or a single attribute from an XML document is straightforward. However, when removing collections of elements or attributes, you should first materialize a collection into a list, and then delete the elements or attributes from the list. The best approach is to use the Remove extension method, which will do this for you.

The main reason for doing this is that most of the collections you retrieve from an XML tree are yielded using deferred execution. If you do not first materialize them into a list, or if you do not use the extension methods, it is possible to encounter a certain class of bugs. For more information, see Mixed Declarative Code/Imperative Code Bugs (C#) (LINQ to XML).

The following methods remove nodes and attributes from an XML tree.




Removes an XAttribute from its parent.


Removes the child nodes from an XContainer.


Removes content and attributes from an XElement.


Removes the attributes of an XElement.


If you pass null for value, then removes the attribute.


If you pass null for value, then removes the child element.


Removes an XNode from its parent.


Removes every attribute or element in the source collection from its parent element.


This example demonstrates three approaches to removing elements. First, it removes a single element. Second, it retrieves a collection of elements, materializes them using the Enumerable.ToList<TSource> operator, and removes the collection. Finally, it retrieves a collection of elements and removes them using the Remove extension method.

For more information on the ToList<TSource> operator, see Converting Data Types.


XElement root = XElement.Parse(@"<Root>


This code produces the following output:

    <GrandChild2 />
    <GrandChild3 />
  <Child2 />
  <Child3 />

Notice that the first grandchild element has been removed from Child1. All grandchildren elements have been removed from Child2 and from Child3.