Working with XML DOM

by Jagadish Pulakhandam on 9/12/2011 12:54:42 PM
Rated 0 from 0 votes
Brief: Demonstrates on loading XML file, adding, updating, deleting nodes etc. using XML DOM (Document Object Model) in .NET
Posted to: XML Programming using .NET
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

Demonstrates the following:
  • using XML DOM classes in .NET
  • Loading an XML file (or document) using XmlDocument class
  • Searching for single/multiple nodes in an XmlDocument (using XPath)
  • Extracting data/values in nodes
  • Retrieving Child Nodes (and values)
  • Retrieving Attributes of nodes (and values)
  • Adding Nodes (at a particular location in an XML Document or to child nodes)
  • Updating Node data/information
  • Deleting specific Nodes
  • Moving Nodes from one place to another in an XML document

Screen shot:



Source code:

001.using System;
002.using System.Collections.Generic;
003.using System.ComponentModel;
004.using System.Data;
005.using System.Drawing;
006.using System.Linq;
007.using System.Text;
008.using System.Windows.Forms;
009. 
010.using System.Xml;
011. 
012.namespace XmlCRUDwithDOM
013.{
014.    public partial class Form1 : Form
015.    {
016.        public Form1()
017.        {
018.            InitializeComponent();
019.        }
020. 
021.        const string XMLDOCFILEPATH = "..\\..\\MyData.xml";
022.        XmlDocument doc;
023. 
024.        private void btnSearch_Click(object sender, EventArgs e)
025.        {
026.            XmlElement nEmp = (XmlElement)doc.SelectSingleNode(string.Format("//Employee[Empno='{0}']", this.txtEmpno.Text));
027.            if (nEmp == null)
028.            {
029.                MessageBox.Show("Not found");
030.                return;
031.            }
032. 
033.            this.txtEname.Text = nEmp.SelectSingleNode("Ename").InnerText;
034.            this.txtSal.Text = nEmp.SelectSingleNode("Sal").InnerText;
035.            this.txtDeptno.Text = nEmp.SelectSingleNode("Deptno").InnerText;
036.            this.txtID.Text = nEmp.GetAttribute("ID");
037.        }
038. 
039.        private void Form1_Load(object sender, EventArgs e)
040.        {
041.            RefreshXMLDoc();
042.        }
043. 
044.        private void RefreshXMLDoc()
045.        {
046.            doc = new XmlDocument();
047.            doc.Load(XMLDOCFILEPATH);
048.            btnRefresh_Click(null, null);
049.        }
050. 
051.        private void SaveXMLDoc()
052.        {
053.            doc.Save(XMLDOCFILEPATH);
054.            RefreshXMLDoc();
055.            btnClear_Click(null, null);
056.        }
057. 
058.        private void btnRefresh_Click(object sender, EventArgs e)
059.        {
060.            XmlNodeList nEmps = doc.SelectNodes("//Employee");
061.            DataTable dt = new DataTable();
062.            dt.Columns.Add("ID");
063.            dt.Columns.Add("Empno");
064.            dt.Columns.Add("Ename");
065.            dt.Columns.Add("Sal");
066.            dt.Columns.Add("Deptno");
067.            foreach (XmlElement nEmp in nEmps)
068.            {
069.                DataRow dr = dt.NewRow();
070.                dr["ID"] = nEmp.GetAttribute("ID");
071.                dr["Empno"] = nEmp.ChildNodes[0].InnerText;
072.                dr["Ename"] = nEmp.ChildNodes[1].InnerText;
073.                dr["Sal"] = nEmp.ChildNodes[2].InnerText;
074.                dr["Deptno"] = nEmp.ChildNodes[3].InnerText;
075.                dt.Rows.Add(dr);
076.            }
077.            this.DataGridView1.DataSource = dt;
078.        }
079. 
080.        private void btnClear_Click(object sender, EventArgs e)
081.        {
082.            foreach (Control c in this.Controls)
083.            {
084.                if (c is TextBox)
085.                {
086.                    ((TextBox)c).Text = "";
087.                }
088.            }
089.        }
090. 
091.        private void btnAdd_Click(object sender, EventArgs e)
092.        {
093.            //go to the EmployeeInfo node of provided department
094.            XmlNode nEmpInfo = doc.SelectSingleNode(string.Format("//Department[Deptno='{0}']/EmployeeInfo", this.txtDeptno.Text));
095.            if (nEmpInfo == null)
096.            {
097.                MessageBox.Show("Department/EmployeeInfo not found");
098.                return;
099.            }
100. 
101.            //create elements of node structure
102.            XmlNode nEmployee = doc.CreateElement("Employee");
103.            XmlNode nEmpno = doc.CreateElement("Empno");
104.            XmlNode nEname = doc.CreateElement("Ename");
105.            XmlNode nSal = doc.CreateElement("Sal");
106.            XmlNode nDeptno = doc.CreateElement("Deptno");
107.            XmlAttribute aID = doc.CreateAttribute("ID");
108. 
109.            //assign values to elements
110.            nEmpno.InnerText = this.txtEmpno.Text;
111.            nEname.InnerText = this.txtEname.Text;
112.            nSal.InnerText = this.txtSal.Text;
113.            nDeptno.InnerText = this.txtDeptno.Text;
114.            aID.InnerText = this.txtID.Text;
115. 
116.            //form the node structure
117.            {
118.                nEmployee.Attributes.Append(aID);
119.                nEmployee.AppendChild(nEmpno);
120.                nEmployee.AppendChild(nEname);
121.                nEmployee.AppendChild(nSal);
122.                nEmployee.AppendChild(nDeptno);
123.            }
124. 
125.            nEmpInfo.AppendChild(nEmployee);
126.            SaveXMLDoc();
127.            MessageBox.Show("Added Succesfully!");
128. 
129.        }
130. 
131.        private void btnUpdate_Click(object sender, EventArgs e)
132.        {
133.            XmlElement nEmp = (XmlElement)doc.SelectSingleNode(string.Format("//Employee[Empno='{0}']", this.txtEmpno.Text));
134.            if (nEmp == null)
135.            {
136.                MessageBox.Show("Not found");
137.                return;
138.            }
139. 
140.            if (nEmp.SelectSingleNode("Deptno").InnerText.Equals(this.txtDeptno.Text))
141.            {
142.                //'The following would simply modify and update the record
143.                //'However, it would not detach and attach to another dept branch (if dept is different)
144.                nEmp.SelectSingleNode("Ename").InnerText = this.txtEname.Text;
145.                nEmp.SelectSingleNode("Sal").InnerText = this.txtSal.Text;
146.                nEmp.SelectSingleNode("Deptno").InnerText = this.txtDeptno.Text;
147.                //this is not necessary
148.                nEmp.SetAttribute("ID", this.txtID.Text);
149.            }
150.            else
151.            {
152.                //go to the EmployeeInfo node of provided department
153.                XmlNode nTargetEmpInfo = doc.SelectSingleNode(string.Format("//Department[Deptno='{0}']/EmployeeInfo", this.txtDeptno.Text));
154.                if (nTargetEmpInfo == null)
155.                {
156.                    MessageBox.Show("Department/EmployeeInfo not found");
157.                    return;
158.                }
159. 
160.                //remove node from current location
161.                XmlElement nSourceEmpInfo = (XmlElement)nEmp.SelectSingleNode("ancestor::EmployeeInfo");
162.                nSourceEmpInfo.RemoveChild(nEmp);
163. 
164.                //addding node to new location
165.                //create elements of node structure
166.                XmlNode nEmployee = doc.CreateElement("Employee");
167.                XmlNode nEmpno = doc.CreateElement("Empno");
168.                XmlNode nEname = doc.CreateElement("Ename");
169.                XmlNode nSal = doc.CreateElement("Sal");
170.                XmlNode nDeptno = doc.CreateElement("Deptno");
171.                XmlAttribute aID = doc.CreateAttribute("ID");
172.                //assign values to elements
173.                nEmpno.InnerText = this.txtEmpno.Text;
174.                nEname.InnerText = this.txtEname.Text;
175.                nSal.InnerText = this.txtSal.Text;
176.                nDeptno.InnerText = this.txtDeptno.Text;
177.                aID.InnerText = this.txtID.Text;
178.                //form the node structure
179.                {
180.                    nEmployee.Attributes.Append(aID);
181.                    nEmployee.AppendChild(nEmpno);
182.                    nEmployee.AppendChild(nEname);
183.                    nEmployee.AppendChild(nSal);
184.                    nEmployee.AppendChild(nDeptno);
185.                }
186.                nTargetEmpInfo.AppendChild(nEmployee);
187. 
188.            }
189. 
190. 
191.            SaveXMLDoc();
192.            MessageBox.Show("Updated Succesfully!");
193.        }
194. 
195.        private void btnDelete_Click(object sender, EventArgs e)
196.        {
197.            XmlElement nEmp = (XmlElement)doc.SelectSingleNode(string.Format("//Employee[Empno='{0}']", this.txtEmpno.Text));
198.            if (nEmp == null)
199.            {
200.                MessageBox.Show("Not found");
201.                return;
202.            }
203.            XmlElement nEmpInfo = (XmlElement)nEmp.SelectSingleNode("ancestor::EmployeeInfo");
204.            nEmpInfo.RemoveChild(nEmp);
205.            SaveXMLDoc();
206.            MessageBox.Show("Deleted Succesfully!");
207.        }
208.    }
209.}


Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
0

Rated 0 from 0 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following