Update XML Element in C#
To update an XML Element in C#, First we load the XML string into an XmlDocument object either from file or From String, then we use methodGetElementsByTagName()
with tag name as parameter. then we select which index we want. Finally we use InnerXml
property to change the element content. You can later either save it or do anything you want to do with new XML.Example
using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
public class Program
{
public static void Main()
{
string test = "<body><head>My Header</head></body>";
XmlDocument xmltest = new XmlDocument();
xmltest.LoadXml(test);
XmlNodeList elemlist = xmltest.GetElementsByTagName("head");
elemlist[0].InnerXml = "My New Value";
xmltest.Save(@"C:\newXML.xml");
Console.WriteLine(xmltest.InnerXml);
}
}