Visual Basic 2005 XML Programming Using XML DOM - Developing a complete form to work with XML DOM using Visual Basic.NET
(Page 5 of 6 )
To demonstrate all of the previous concepts, I designed a Windows form for CRUD operations as shown in Fig 1. The following is the code developed for the form:
Imports System.Xml
Public Class Form1
Const XMLDOCFILEPATH As String = "....MyData.xml"
Dim doc As New XmlDocument
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Dim nEmp As XmlElement = doc.SelectSingleNode(String.Format("//Employee[Empno='{0}']", Me.txtEmpno.Text))
If nEmp Is Nothing Then
MessageBox.Show("Not found")
Exit Sub
End If
Me.txtEname.Text = nEmp.SelectSingleNode("Ename").InnerText
Me.txtSal.Text = nEmp.SelectSingleNode("Sal").InnerText
Me.txtDeptno.Text = nEmp.SelectSingleNode("Deptno").InnerText
Me.txtID.Text = nEmp.GetAttribute("ID")
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
RefreshXMLDoc()
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
For Each c As Control In Me.Controls
If TypeOf c Is TextBox Then
CType(c, TextBox).Text = ""
End If
Next
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
'go to the EmployeeInfo node of provided department
Dim nEmpInfo As XmlNode = doc.SelectSingleNode(String.Format("//Department[Deptno='{0}']/EmployeeInfo", Me.txtDeptno.Text))
If nEmpInfo Is Nothing Then
MessageBox.Show("Department/EmployeeInfo not found")
Exit Sub
End If
'create elements of node structure
Dim nEmployee As XmlNode = doc.CreateElement("Employee")
Dim nEmpno As XmlNode = doc.CreateElement("Empno")
Dim nEname As XmlNode = doc.CreateElement("Ename")
Dim nSal As XmlNode = doc.CreateElement("Sal")
Dim nDeptno As XmlNode = doc.CreateElement("Deptno")
Dim aID As XmlAttribute = doc.CreateAttribute("ID")
'assign values to elements
nEmpno.InnerText = Me.txtEmpno.Text
nEname.InnerText = Me.txtEname.Text
nSal.InnerText = Me.txtSal.Text
nDeptno.InnerText = Me.txtDeptno.Text
aID.InnerText = Me.txtID.Text
'form the node structure
With nEmployee
.Attributes.Append(aID)
.AppendChild(nEmpno)
.AppendChild(nEname)
.AppendChild(nSal)
.AppendChild(nDeptno)
End With
nEmpInfo.AppendChild(nEmployee)
SaveXMLDoc()
MessageBox.Show("Added Successfully!")
End Sub
Private Sub SaveXMLDoc()
doc.Save(XMLDOCFILEPATH)
RefreshXMLDoc()
btnClear_Click(Nothing, Nothing)
End Sub
Private Sub RefreshXMLDoc()
doc = New XmlDocument
doc.Load(XMLDOCFILEPATH)
btnRefresh_Click(Nothing, Nothing)
End Sub
Next: Developing a complete form to work with XML DOM using Visual Basic.NET: continued >>
More Windows Scripting Articles
More By Jagadish Chaterjee