Create and Update XML File

Introduction:

Xml stands for Extensible Markup Language. All the Tags/Elements of Xml are user defined that’s why it is Easy to Create and understand.

Important:

To Create XML we have used following Class and Methods. XmlDocumant class is present under System.Xml namespace.

Classes:

  • XmlDocument
  • XmlDeclaration
  • XmlElement

Methods:

  • CreateElement()
  • AppendChild()

Example:

In Example, we have Created XML having 2 Element Id & Name using Windows Application.

Open Visual Studio and Design a form like this:



Add Following Codes on “Save” Button_click :

  1. namespace Xml_Proc  
  2. {  
  3.     public partial class Form1 : Form  
  4.     {  
  5.         public Form1()  
  6.         {  
  7.             InitializeComponent();  
  8.         }  
  9.         private XmlElement root;  
  10.         public string path = @"C:\Users\kundan\Desktop\Sample.xml";  
  11.         XmlDocument doc = new XmlDocument();  
  12.   
  13.         private void button1_Click(object sender, EventArgs e)  
  14.         {  
  15.             if (!File.Exists(path))  
  16.             {  
  17.                 XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0""UTF-8""yes");  
  18.                 root = doc.CreateElement("Employee");  
  19.                 XmlElement Emp = doc.CreateElement("Emp");  
  20.                 XmlElement ID = doc.CreateElement("ID");  
  21.                 XmlElement NAME = doc.CreateElement("NAME");  
  22.   
  23.                 ID.InnerText = textBox1.Text;  
  24.                 NAME.InnerText = textBox2.Text;  
  25.   
  26.                 doc.AppendChild(declaration);  
  27.                 doc.AppendChild(root);  
  28.                 root.AppendChild(Emp);  
  29.                 Emp.AppendChild(ID);  
  30.                 Emp.AppendChild(NAME);  
  31.   
  32.                 doc.Save(path);  
  33.   
  34.                 MessageBox.Show("XML Created && Data has been Inserted");  
  35.             }  
  36.             else  
  37.             {  
  38.                 doc = new XmlDocument();  
  39.                 doc.Load(path);  
  40.                 root = doc.DocumentElement;  
  41.                 XmlElement Emp = doc.CreateElement("Emp");  
  42.                 XmlElement ID = doc.CreateElement("ID");  
  43.                 XmlElement NAME = doc.CreateElement("NAME");  
  44.                 ID.InnerText = textBox1.Text;  
  45.                 NAME.InnerText = textBox2.Text;  
  46.                 Emp.AppendChild(ID);  
  47.                 Emp.AppendChild(NAME);  
  48.                 root.AppendChild(Emp);  
  49.                 doc.Save(path);  
  50.                 MessageBox.Show("XML Updated");  
  51.             }  
  52.         }  
  53.     }  
  54. }  
Output will look like: