Visual Basic 2005 XML Programming Using XML DOM - Adding, Updating and Deleting From the XML Document with XML DOM Using Visual Basic.NET
(Page 4 of 6 )
In the previous section, we have seen how to retrieve and search an XML document using XML DOM. In this section we will manipulate the XML document with Add, Update and Delete operations.
Let us consider adding a new employee to department 30. The following is the sample code:
Dim nEmpInfo As XmlNode = doc.SelectSingleNode("//Department[Deptno='30']/EmployeeInfo")
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 = "4001"
nEname.InnerText = "Winner"
nSal.InnerText = "4500"
nDeptno.InnerText = "30"
aID.InnerText = "E20"
'form the node structure
With nEmployee
.Attributes.Append(aID)
.AppendChild(nEmpno)
.AppendChild(nEname)
.AppendChild(nSal)
.AppendChild(nDeptno)
End With
nEmpInfo.AppendChild(nEmployee)
Similarly, we can also modify existing record information using the following code:
Dim nEmp As XmlElement = doc.SelectSingleNode("//Employee[Empno='4001']")
nEmp.SelectSingleNode("Ename").InnerText = "Winner2"
nEmp.SelectSingleNode("Sal").InnerText = "5400"
nEmp.SelectSingleNode("Deptno").InnerText = "30"
nEmp.SetAttribute("ID", "E40")
In the same manner, we can use the following code to delete existing record:
Dim nEmp As XmlElement = doc.SelectSingleNode("//Employee[Empno='4001']")
Dim nEmpInfo As XmlElement = nEmp.SelectSingleNode("ancestor::EmployeeInfo")
nEmpInfo.RemoveChild(nEmp)
Finally, we can save the XML document back to the file using the following code:
doc.Save(XMLDOCFILEPATH)
Next: Developing a complete form to work with XML DOM using Visual Basic.NET >>
More Windows Scripting Articles
More By Jagadish Chaterjee