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. private void button1_Click(object sender, EventArgs e)
  13. {
  14. if (!File.Exists(path))
  15. {
  16. XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
  17. root = doc.CreateElement("Employee");
  18. XmlElement Emp = doc.CreateElement("Emp");
  19. XmlElement ID = doc.CreateElement("ID");
  20. XmlElement NAME = doc.CreateElement("NAME");
  21. ID.InnerText = textBox1.Text;
  22. NAME.InnerText = textBox2.Text;
  23. doc.AppendChild(declaration);
  24. doc.AppendChild(root);
  25. root.AppendChild(Emp);
  26. Emp.AppendChild(ID);
  27. Emp.AppendChild(NAME);
  28. doc.Save(path);
  29. MessageBox.Show("XML Created && Data has been Inserted");
  30. }
  31. else
  32. {
  33. doc = new XmlDocument();
  34. doc.Load(path);
  35. root = doc.DocumentElement;
  36. XmlElement Emp = doc.CreateElement("Emp");
  37. XmlElement ID = doc.CreateElement("ID");
  38. XmlElement NAME = doc.CreateElement("NAME");
  39. ID.InnerText = textBox1.Text;
  40. NAME.InnerText = textBox2.Text;
  41. Emp.AppendChild(ID);
  42. Emp.AppendChild(NAME);
  43. root.AppendChild(Emp);
  44. doc.Save(path);
  45. MessageBox.Show("XML Updated");
  46. }
  47. }
  48. }
  49. }
Output will look like: