在C#中移除XML元素属性最推荐使用LINQ to XML:定位元素后调用Attribute("name")?.Remove();批量删除用Descendants().Attributes("name").Remove();传统XmlDocument则用RemoveAttribute()。
在C#中移除XML元素的某个属性,最常用且推荐的方式是使用 System.Xml.Linq(即 LINQ to XML

Attribute("属性名")?.Remove() 即可安全删除。
这是最常用的方法,适用于已加载为 XElement 或 XDocument 的XML:
Element("TagName") 或 Descendants("TagName") 找到目标元素Attribute("AttributeName") 获取指定属性(返回 XAttribute 或 null).Remove() 删除该属性(支持空值安全调用:?.Remove())示例:
XDocument doc = XDocument.Load("data.xml");
XElement target = doc.Root?.Element("User"); // 假设根下有个
target?.Attribute("id")?.Remove(); // 移除 id 属性
doc.Save("data.xml");
如果要删掉整个文档中所有 class 属性,可用 Descendants() 配合 Attributes():
doc.Descendants().Attributes("class") 返回所有匹配属性集合.Remove() 即可全部删除示例:
doc.Descendants().Attributes("class").Remove(); // 一行搞定
若项目仍在用老式 XmlDocument,也可实现,但代码稍长:
SelectSingleNode() 或 GetElementsByTagName() 找到 XmlElement
HasAttribute("attrName"),再调用 RemoveAttribute("attrName")
示例:
XmlDocument doc = new XmlDocument();
doc.Load("data.xml");
XmlElement elem = doc.SelectSingleNode("/Root/User") as XmlElement;
if (elem != null && elem.HasAttribute("id"))
{
elem.RemoveAttribute("id");
}
doc.Save("data.xml");
移除前无需手动判空——用 ?.Remove() 就足够安全;但要注意:
"ID" 和 "id" 是不同的Remove() 是就地修改,不返回新对象,也不影响其他引用(除非共享同一实例)基本上就这些。LINQ to XML 方式更推荐,写起来干净,读起来清楚,不容易漏判空。