How to remove all child nodes of an XmlElement, but keep all attributes?

usr picture usr · Apr 10, 2013 · Viewed 11.7k times · Source

How to remove all child nodes of an XmlElement, but keep all attributes?

Note, that XmlElement.RemoveAll also removes all attributes. What is a clean, elegant and well-performing way to remove all child nodes? In other words, what is best-practice here?

Answer

Parsley picture Parsley · Mar 27, 2014

For a truly efficient solution:

e.IsEmpty = true;

is your fastest and simplest option. It does exactly what you requested: all inner text and nested elements are discarded, while attributes are retained.