Stefan Filip
Stefan Filip

Reputation: 1801

What's the easiest way to remove all attributes from a XML in C#?

I want to remove the attributes of all tags from a XML (I want to keep only the tags and their inner value). What's the easiest way to do this in C#?

Upvotes: 11

Views: 7862

Answers (3)

Ruina
Ruina

Reputation: 365

It's faster if you use a better XPath like "//*[@*]"

foreach (XmlElement el in nodes.SelectNodes("//*[@*]")) {
   el.Attributes.RemoveAll();
}

This will limit the results to just elements that have attributes.

Upvotes: 1

Ivo
Ivo

Reputation: 3436

foreach (XmlElement el in nodes.SelectNodes(".//*")) {
   el.Attributes.RemoveAll();
}

Upvotes: 5

Lasse Espeholt
Lasse Espeholt

Reputation: 17782

static void removeAllAttributes(XDocument doc)
{
    foreach (var des in doc.Descendants())
        des.RemoveAttributes();
}

Usage:

var doc = XDocument.Load(path); //Or .Parse("xml");
removeAllAttributes(doc);

string res = doc.ToString();

Upvotes: 6

Related Questions