How to change XML Attribute in C#?
To change an XML Attribute in C# we will need to do below steps:- 1) we should be using
using System.Xml;
- 2) Define an
XmlDocument
- 3) Load XML file using method Load() defined in
XmlDocument
. - 4) Define an
XmlNode
Object by using methodxmlDoc.SelectSingleNode()
- 5) Update the value to the node.
- 6) Save the file using same filename.
Example of change XML Attribute in C#
using System.Xml;
public class Example
{
public static void Main()
{
string xmlFile = @"C:\File_Path";
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);
}
}