如何更改XML属性

60 c# xml xmldocument linq-to-xml

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

El *_*ino 67

麦克风; 每次我需要修改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
Run Code Online (Sandbox Code Playgroud)

希望对你有帮助


ale*_*mac 61

如果您使用框架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");
Run Code Online (Sandbox Code Playgroud)


Ahm*_*mad 13

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

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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

用法:

   XmlAttribute attr = dom.CreateAttribute("name");
   attr.Value = value;
   SetAttrSafe(node, attr);
Run Code Online (Sandbox Code Playgroud)