LINQ to XML Programming Using Visual Basic.NET 2008 - Developing a complete form to work with LINQ to XML using Visual Basic 2008: continued
(Page 5 of 6 )
The following continues from the previous section.
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
Dim qEmp As XElement = doc.Descendants.Elements("Employee") _
.Where(Function(xe) xe.<Empno>.Value = Me.txtEmpno.Text) _
.FirstOrDefault
If qEmp Is Nothing Then
MessageBox.Show("Not found")
Exit Sub
End If
qEmp.Remove()
SaveXMLDoc()
MessageBox.Show("Deleted Successfully!")
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim qEmp As XElement = doc.Descendants.Elements("Employee") _
.Where(Function(xe) xe.<Empno>.Value = Me.txtEmpno.Text) _
.FirstOrDefault
If qEmp Is Nothing Then
MessageBox.Show("Not found")
Exit Sub
End If
If qEmp.<Deptno>.Value.Equals(Me.txtDeptno.Text) Then
''The following would simply modify and update the record
''However, it would not detach and attach to another dept branch (if dept is different)
qEmp.<Ename>.Value = Me.txtEname.Text
qEmp.<Sal>.Value = Me.txtSal.Text
qEmp.<Deptno>.Value = Me.txtDeptno.Text 'this is not necessary
qEmp.@ID = Me.txtID.Text
Else
'go to the Department node of provided department
Dim qTargetDept As XElement = doc.Descendants.Elements("Department") _
.Where(Function(xe) xe.<Deptno>.Value = Me.txtDeptno.Text) _
.FirstOrDefault
If qTargetDept Is Nothing Then
MessageBox.Show("Department/EmployeeInfo not found")
Exit Sub
End If
'remove node from current location
qEmp.Remove()
'adding node to new location
Dim oEmp As New XElement("Employee")
oEmp.Add(New XAttribute("ID", Me.txtID.Text))
oEmp.Add(New XElement("Empno", Me.txtEmpno.Text))
oEmp.Add(New XElement("Ename", Me.txtEname.Text))
oEmp.Add(New XElement("Sal", Me.txtSal.Text))
oEmp.Add(New XElement("Deptno", Me.txtDeptno.Text))
qTargetDept.Element("EmployeeInfo").Add(oEmp)
End If
SaveXMLDoc()
MessageBox.Show("Updated Successfully!")
End Sub
Private Sub RefreshXDoc()
doc = XDocument.Load(XMLDOCFILEPATH)
btnRefresh_Click(Nothing, Nothing)
End Sub
Private Sub SaveXMLDoc()
doc.Save(XMLDOCFILEPATH)
RefreshXDoc()
btnClear_Click(Nothing, Nothing)
End Sub
End Class
Next: How to use XPath expressions in LINQ to XML >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee