如何更改XML属性

如何使用C#更改XML文件中某个元素的属性?

麦克风; 每次我需要修改一个XML文档时,都是这样工作的:

//Here is the variable with which you assign a new value to the attribute string newValue = string.Empty; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlFile); XmlNode node = xmlDoc.SelectSingleNode("Root/Node/Element"); node.Attributes[0].Value = newValue; xmlDoc.Save(xmlFile); //xmlFile is the path of your file to be modified 

希望对你有帮助

如果您使用的是框架3.5,则使用LINQ to xml:

 using System.Xml.Linq; XDocument xmlFile = XDocument.Load("books.xml"); var query = from c in xmlFile.Elements("catalog").Elements("book") select c; foreach (XElement book in query) { book.Attribute("attr1").Value = "MyNewValue"; } xmlFile.Save("books.xml"); 

如果您要更改的属性不存在或意外删除,则会发生exception。 我build议你先创build一个新的属性,并将其发送到如下的函数:

 private void SetAttrSafe(XmlNode node,params XmlAttribute[] attrList) { foreach (var attr in attrList) { if (node.Attributes[attr.Name] != null) { node.Attributes[attr.Name].Value = attr.Value; } else { node.Attributes.Append(attr); } } } 

用法:

  XmlAttribute attr = dom.CreateAttribute("name"); attr.Value = value; SetAttrSafe(node, attr);