答案:可通过XmlDocument或XDocument修改XML属性。使用XmlDocument需手动检查属性并创建,而XDocument的SetAttributeValue方法可自动添加或更新属性,操作更简洁。

在C#中操作XML节点的属性,可以通过 XmlDocument 或 XDocument(LINQ to XML)来实现。下面分别介绍这两种常用方式如何设置或修改XML节点的属性。
使用 XmlDocument 设置或修改属性
XmlDocument 是传统的XML操作类,适合处理较复杂的XML文档结构。假设有一个XML文档如下:
你想将 Person 节点的 Name 属性改为 "Bob",或者添加一个新的属性 Age="25",可以这样做:
XmlDocument doc = new XmlDocument();
doc.Load("test.xml"); // 或 LoadXml("...");
XmlNode personNode = doc.SelectSingleNode("/Root/Person");
if (personNode != null && personNode.Attributes != null)
{
// 修改现有属性
XmlAttribute nameAttr = personNode.Attributes["Name"];
if (nameAttr != null)
nameAttr.Value = "Bob";
// 添加或设置新属性
XmlAttribute ageAttr = personNode.Attributes["Age"];
if (ageAttr == null)
{
ageAttr = doc.CreateAttribute("Age");
personNode.Attributes.Append(ageAttr);
}
ageAttr.Value = "25";
}
doc.Save("test.xml"); // 保存更改
使用 XDocument(LINQ to XML)设置或修改属性
XDocument 更现代、语法更简洁,推荐用于新项目。同样的XML内容,用 XDocument 操作会更直观:
XDocument doc = XDocument.Load("test.xml");
var person = doc.Root?.Element("Person");
if (person != null)
{
// 修改现有属性
person.SetAttributeValue("Name", "Bob");
// 设置新属性(如果不存在则添加,存在则更新)
person.SetAttributeValue("Age", "25");
}
doc.Save("test.xml");
SetAttributeValue 方法非常方便:属性不存在就创建,存在就更新,无需判断。
注意事项
- 属性名区分大小写,确保拼写一致。
- 修改后记得调用 Save() 方法保存文件。
- 操作前建议检查节点是否为 null,避免 NullReferenceException。
- 若要删除属性,可调用 RemoveAttribute("AttributeName")(XmlDocument)或设置属性值为 null(XDocument 中 SetAttributeValue(key, null) 会移除该属性)。










