LINQ to XML Programming Using Visual Basic.NET 2008 - Adding, Updating and Deleting from an XML document using LINQ to XML
(Page 3 of 6 )
In previous section, we saw how to retrieve and search an XML document using "LINQ to XML." In this section we will manipulate an 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 qTargetDept As XElement = doc.Descendants.Elements("Department") _
.Where(Function(xe) xe.<Deptno>.Value = "30") _
.FirstOrDefault
If qTargetDept Is Nothing Then
MessageBox.Show("Department/EmployeeInfo not found")
Exit Sub
End If
Dim oEmp As New XElement("Employee")
oEmp.Add(New XAttribute("ID", "E20"))
oEmp.Add(New XElement("Empno", "4001"))
oEmp.Add(New XElement("Ename", "Winner"))
oEmp.Add(New XElement("Sal", "4500"))
oEmp.Add(New XElement("Deptno", "30"))
qTargetDept.Element("EmployeeInfo").Add(oEmp)
In the above code snippet, I am using the "XElement" class instead of the "XMLElement" class. "XElement" belongs to "System.Linq."
Similarly, we can also modify existing records using the following code:
Dim qEmp As XElement = doc.Descendants.Elements("Employee") _
.Where(Function(xe) xe.<Empno>.Value = "4001") _
.FirstOrDefault
qEmp.<Ename>.Value = "Winner2"
qEmp.<Sal>.Value = "5400"
qEmp.<Deptno>.Value = "30" 'this is not necessary
qEmp.@ID = "E40"
In the same manner, we can use the following code to delete an existing record:
Dim qEmp As XElement = doc.Descendants.Elements("Employee") _
.Where(Function(xe) xe.<Empno>.Value = "4001") _
.FirstOrDefault
qEmp.Remove()
Finally, we can save the XML document back to the file using the following code:
doc.Save(XMLDOCFILEPATH)
Make sure that "Save" is still supported in "XDocument" and it works in the same manner as "XMLDocument.Save" does.
Next: Developing a complete form to work with LINQ to XML using Visual Basic 2008 >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee