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 :
- namespace Xml_Proc
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private XmlElement root;
- public string path = @"C:\Users\kundan\Desktop\Sample.xml";
- XmlDocument doc = new XmlDocument();
-
- private void button1_Click(object sender, EventArgs e)
- {
- if (!File.Exists(path))
- {
- XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
- root = doc.CreateElement("Employee");
- XmlElement Emp = doc.CreateElement("Emp");
- XmlElement ID = doc.CreateElement("ID");
- XmlElement NAME = doc.CreateElement("NAME");
-
- ID.InnerText = textBox1.Text;
- NAME.InnerText = textBox2.Text;
-
- doc.AppendChild(declaration);
- doc.AppendChild(root);
- root.AppendChild(Emp);
- Emp.AppendChild(ID);
- Emp.AppendChild(NAME);
-
- doc.Save(path);
-
- MessageBox.Show("XML Created && Data has been Inserted");
- }
- else
- {
- doc = new XmlDocument();
- doc.Load(path);
- root = doc.DocumentElement;
- XmlElement Emp = doc.CreateElement("Emp");
- XmlElement ID = doc.CreateElement("ID");
- XmlElement NAME = doc.CreateElement("NAME");
- ID.InnerText = textBox1.Text;
- NAME.InnerText = textBox2.Text;
- Emp.AppendChild(ID);
- Emp.AppendChild(NAME);
- root.AppendChild(Emp);
- doc.Save(path);
- MessageBox.Show("XML Updated");
- }
- }
- }
- }
Output will look like: