开发者

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

开发者 https://www.devze.com 2023-01-12 21:42 出处:网络
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 th开发者_运维知识库is in C#?static void removeAllAttributes(X

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 th开发者_运维知识库is in C#?


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();


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消