Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

parsing

xml

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#?

like image 975
Stefan Filip Avatar asked Aug 23 '10 09:08

Stefan Filip


People also ask

How to remove elements from XML?

Remove a Text Node xml is loaded into xmlDoc. Set the variable x to be the first title element node. Set the variable y to be the text node to remove. Remove the element node by using the removeChild() method from the parent node.

How do I clear XML?

In the XML Source task pane, click XML Maps. The XML Maps dialog box is displayed. Select the XML map that you want to delete. Click Delete, and then click OK.

Can XML attributes be empty?

An element with no content is said to be empty. The two forms produce identical results in XML software (Readers, Parsers, Browsers). Empty elements can have attributes.

Why do you avoid XML attributes?

Why should we avoid XML attributes. Attributes cannot contain multiple values but child elements can have multiple values. Attributes cannot contain tree structure but child element can. Attributes are not easily expandable.


2 Answers

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();
like image 120
Lasse Espeholt Avatar answered Oct 10 '22 12:10

Lasse Espeholt


foreach (XmlElement el in nodes.SelectNodes(".//*")) {
   el.Attributes.RemoveAll();
}
like image 41
Ivo Avatar answered Oct 10 '22 14:10

Ivo