You can modify a xml file with a tag name using below simple code snippet.
XML File:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?xml version="1.0" encoding="utf-8"?> <Books> <book> <title>Sleep Research</title> <pages>300</pages> <price>100</price> </book> <book> <title>Sleep and Memory</title> <pages>400</pages> <price>200</price> </book> <book> <title>Parenting Guide</title> <pages>500</pages> <price>300</price> </book> </Books> |
C# Program to Modify above xml file accessing using a tag name.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System; //C# Program to modify xml file //Access the tag with tagname and modify the value. namespace ProgramCall { class Program { static void Main(string[] args) { //Make sure xml file and Application exe are in same directory //If you are running in debug mode in visual studio, xml file should be present in debug directory. string filePath="XMLFile1.xml"; System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.Load(filePath); System.Xml.XmlNodeList elemList = doc.GetElementsByTagName("title"); if (elemList != null && elemList.Count > 0) { elemList[0].InnerText = "Sleep Research"; elemList[1].InnerText = "Sleep and Memory"; elemList[2].InnerText = "Parenting Guide"; } doc.Save(filePath); } } } |