如何使用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");
如果要更改的属性不存在或意外删除,则会发生异常.我建议你先创建一个新属性并将其发送到如下函数:
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);