As I saw So many new developers are asking similar question so thought of writing this blog.
So to made it bit user friendly, I put 3 text box, where you can enter the values and by clicking "Save value in XML" button, you can save the values in XML format. Currently I am using @"C:\xmlfile.xml" for file path, so you can modify this as per your requirement. I have also added 1 list view and 1 list box, where you can get the values from XML by clicking "RetrieveItems" button.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Windows.Forms;
- using System.Xml;
-
- namespace WindowsFormsApplication1
- {
- public partial class Form1 : Form
- {
- private const string FilePath = @"C:\xmlfile.xml";
-
- public Form1()
- {
- InitializeComponent();
- }
-
-
-
-
-
-
- private void btnSaveValuesInXML_Click(object sender, EventArgs e)
- {
-
- var textWriter = new XmlTextWriter(FilePath, null);
-
- textWriter.WriteStartDocument();
-
- textWriter.WriteComment("First Comment for XmlTextWriter Sample Example");
-
- textWriter.WriteStartElement("Student");
-
-
- textWriter.WriteStartElement("Name");
- textWriter.WriteString(textBox1.Text);
- textWriter.WriteEndElement();
-
- textWriter.WriteStartElement("Address");
- textWriter.WriteString(textBox2.Text);
- textWriter.WriteEndElement();
-
- textWriter.WriteStartElement("Pincode");
- textWriter.WriteString(textBox3.Text);
- textWriter.WriteEndElement();
-
- textWriter.WriteEndDocument();
-
- textWriter.Close();
- MessageBox.Show(@"Values got stored in XML");
- }
-
-
-
-
-
-
- private void btnRetrieveItems_Click(object sender, EventArgs e)
- {
- var doc = new XmlDocument();
- doc.Load(FilePath);
-
- var nodeNames = new List<string>();
- var xmlNodeList = doc.SelectNodes("/Student");
-
-
-
-
-
-
-
-
-
-
-
-
- if (xmlNodeList != null)
- nodeNames.AddRange(from XmlNode node in xmlNodeList
- from XmlNode child in node.ChildNodes
- select child.InnerText);
-
- foreach (var node in nodeNames)
- {
- listView1.Items.Add(node);
- listBox1.Items.Add(node);
- }
-
- }
- }
- }