Search code examples
.netxmldocumentxmldom

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


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?


Solution

  • 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.