Home

Operations on XML Elements

 

Fundamental Operations

 

Introduction

So far, to create an XML element, we were directly typing in a file. When such a file had been created and saved, it was ready to be processed. Here is an example of a file named videos.xml:

<?xml version="1.0" encoding="utf-8" ?>
<videos>
  <title>The Distinguished Gentleman</title>
</videos>

In some applications, you will want the user to provide you with the necessary value(s) to create an element. Fortunately, the XmlDocument, the XmlNode, and the XmlElement classes provide all the necessary properties and methods to perform the routine operations of an XML file, an element, or a node. The operations include locating a node, adding a new element, or deleting a node.

Before performing an operation, you will usually need to decide in what section of the file you want the action to be applied. As it happens, you have on the root node, on a particular node inside the document, on the parent of a node, on a sibling of a node, etc. To get to a node, you will usually first get a reference to its XmlElement object. To do this, you can declare an XmlElement variable and initialize it with that reference.

 

Practical LearningPractical Learning: Introducing operations on XML Elements

  1. Start Microsoft Visual Basic and create a new Windows Forms Application named SolasPropertyRental1
  2. To add a new form to the application, in the Solution Explorer, right-click SolasPropertyRental1 -> Add -> Windows Form...
  3. Set the Name to Tenants and click Add
  4. From the Toolbox, add a ListView to the form
  5. While the new list view is still selected, in the Properties window, click the ellipsis button of the Columns field and create the columns as follows:
     
    (Name) Text TextAlign Width
    colAccountNumber Account #   65
    colFullName Full Name   120
    colMaritalStatus Marital Status   85
    colPhoneNumber Phone # Center 85
  6. Design the form as follows: 
     
    Solas Property Rental: Customers
     
    Control Text Name Other Properties
    ListView   lvwTenants Anchor: Top, Bottom, Left, Right
    FullRowSelect: True
    GridLines: True
    View: Details
    Button New Tenant... btnNewTenant Anchor: Bottom, Right
    Button Close btnClose Anchor: Bottom, Right
  7. Right-click the Tenants form and click View Code
  8. Import the System.IO and the System.Xml namespaces:
     
    Imports System.IO
    Imports System.Xml
    
    Public Class Tenants
    
    End Class
  9. Just above the End Class line, define a new procedure as follows:
     
    Private Sub ShowTenants()
        Dim Filename As String = "C:\Solas Property Rental\tenants.xml"
        Dim docTenants As XmlDocument = New XmlDocument
    
        If File.Exists(Filename) Then
            lvwTenants.Items.Clear()
    
            docTenants.Load(Filename)
            Dim TenantElement As XmlElement = docTenants.DocumentElement
            Dim ListOfTenants As XmlNodeList = TenantElement.ChildNodes
    
            For Each Node As XmlNode In ListOfTenants
                Dim lviTenant As ListViewItem = New ListViewItem(Node.FirstChild.InnerText) ' Account Number
    
                lviTenant.SubItems.Add(Node.FirstChild.NextSibling.InnerText) ' Full Name
                lviTenant.SubItems.Add(Node.FirstChild.NextSibling.NextSibling.InnerText) ' Phone Number
                lviTenant.SubItems.Add(Node.FirstChild.NextSibling.NextSibling.NextSibling.InnerText) ' Marital Status
                lvwTenants.Items.Add(lviTenant)
            Next
        End If
    End Sub
  10. In the Class Name combo box, select (Tenants Events)
  11. In the Method Name combo box, select Load and implement the event as follows:
     
    Private Sub Tenants_Load(ByVal sender As Object, _
                                 ByVal e As System.EventArgs) _
                                 Handles Me.Load
        ShowTenants()
    End Sub
  12. To add another form to the application, in the Solution Explorer, right-click SolasPropertyRental1 -> Add -> Windows Form...
  13. Set the Name to TenantEditor and click Add
  14. Design the form as follows: 
     
    Solas Property Rental: Customer Editor
     
    Control Text Name Properties
    Label &Account #:    
    MaskedTextBox   txtAccountNumber Mask: 00-00-00
    Modifiers: public
    Label &Full Name:    
    TextBox   txtFullName Modifiers: public
    Label Marital Status:    
    ComboBox   txtMaritalStatus Modifiers: public
    Items:
    Single
    Widow
    Married
    Divorced
    Separated
    Label &Phone #:    
    MaskedTextBox   txtPhoneNumber Mask: (999) 000-0000
    Modifiers: public
    Button OK btnOK DialogResult: OK
    Button Cancel btnCancel DialogResult: Cancel
    Form     AcceptButton: btnOK
    CancelButton: btnCancel
    FormBorderStyle: FixedDialog
    MaximizeBox: False
    MinimizeBox: False
    ShowInTaskbar: False
  15. To add a new form to the application, in the Solution Explorer, right- click SolasPropertyRental4 -> Add -> Windows Form...
  16. Set the Name to RentalProperties and press Enter
  17. From the Toolbox, add a ListView to the form
  18. While the new list view is still selected, in the Properties window, click the ellipsis button of the Columns field and create the columns as follows:
     
    (Name) Text TextAlign Width
    colPropertyCode Prop Code   65
    colPropertyType Property Type   85
    colBedrooms Bedrooms Right 65
    colBathrooms Bathrooms Right 65
    colMonthlyRent Monthly Rent Right 75
    colStatus Status   65
  19. Design the form as follows: 
     
    Solas Property Rental: Properties
     
    Control Text Name Other Properties
    ListView   lvwProperties View: Details
    GridLines: True
    FullRowSelect: True
    Anchor: Top, Bottom, Left, Right
    Button New Property... btnNewProperty Anchor: Bottom, Right
    Button Close btnClose Anchor: Bottom, Right
  20. Right-click the Tenants form and click View Code
  21. Import the System.IO and the System.Xml namespaces:
     
    Imports System.IO
    Imports System.Xml
    
    Public Class RentalProperties
    
    End Class
  22. Just above the End Class line, define a new procedure as follows:
     
    Private Sub ShowProperties()
        Dim DOMProperties As XmlDocument = New XmlDocument
        Dim Filename As String = "C:\Solas Property Rental\properties.xml"
    
        If File.Exists(Filename) Then
            lvwProperties.Items.Clear()
    
            DOMProperties.Load(Filename)
            Dim RootProperty As XmlElement = DOMProperties.DocumentElement
            Dim ListOfProperties As XmlNodeList = RootProperty.ChildNodes
    
            For Each Node As XmlNode In ListOfProperties
                Dim lviProperty As ListViewItem = New ListViewItem(Node.FirstChild.InnerText) ' Property Code
    
                lviProperty.SubItems.Add(Node.FirstChild.NextSibling.InnerText) ' Property Type
                lviProperty.SubItems.Add(Node.FirstChild.NextSibling.NextSibling.InnerText) ' Bedrooms
                lviProperty.SubItems.Add(Node.FirstChild.NextSibling.NextSibling.NextSibling.InnerText) ' Bathrooms
                lviProperty.SubItems.Add(Node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.InnerText) ' Monthly Rent
                lviProperty.SubItems.Add(Node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText) ' Status
                lvwProperties.Items.Add(lviProperty)
            Next
        End If
    End Sub
  23. In the Class Name combo box, select (RentalProperties Events)
  24. In the Method Name combo box, select Load and implement the event as follows:
     
    Private Sub RentalProperties_Load(ByVal sender As Object, _
                                          ByVal e As System.EventArgs) _
                                          Handles Me.Load
        ShowProperties()
    End Sub
  25. To add another form to the application, in the Solution Explorer, right- click SolasPropertyRental1 -> Add -> Windows Form...
  26. Set the Name to PropertyEditor and click Add
  27. Design the form as follows: 
     
    Solas Property Rental: Property Editor
     
    Control Text Name Properties
    Label Property Code:    
    MaskedTextBox   txtPropertyCode Mask: 000-000
    Modifiers: Public
    Button OK btnOK DialogResult: OK
    Label Property Type:    
    ComboBox   cbxPropertyTypes Modifiers: Public
    Items: Unknown
    Apartment
    Townhouse
    Single Family
    Button Cancel btnCancel DialogResult: Cancel
    Label Bedrooms:    
    TextBox 0 txtBedrooms TextAlign: Right
    Modifiers: Public
    Label Bathrooms:    
    TextBox 0.00 txtBathrooms TextAlign: Right
    Modifiers: Public
    Label Monthly Rent:    
    TextBox 0.00 txtMonthlyRent TextAlign: Right
    Modifiers: Public
    Label Occupancy Status:    
    ComboBox Unknown cbxStatus Modifiers: Public
    Items:
    Unknown
    Available
    Occupied
    Needs Repair
    Form     AcceptButton: btnOK
    CancelButton: btnCancel
    FormBorderStyle: FixedDialog
    MaximizeBox: False
    MinimizeBox: False
    ShowInTaskbar: False
  28. To add a new form to the application, in the Solution Explorer, right-click SolasPropertyRental1 -> Add -> Windows Form...
  29. Set the Name to RentalAllocation and click Add
  30. Design the form as follows:
     
    Solas Property Rental: Rental Allocation
    Control Text Name Other Properties
    Label Rent Allocation   AutoSize: False
    BackColor: Gray
    BorderStyle: FixedSingle
    ForeColor: White
    TextAlign: MiddleLeft
    Label Allocation Code:    
    MaskedTextBox   txtAllocationCode Mask: 0000-9999
    Modifiers: Public
    Label Date Allocated:    
    DateTimePicker   dtpDateAllocated Format: Short
    Modifiers: Public
    Label Tenant   AutoSize: False
    BackColor: Gray
    BorderStyle: FixedSingle
    ForeColor: White
    TextAlign: MiddleLeft
    Label Property   AutoSize: False
    BackColor: Gray
    BorderStyle: FixedSingle
    ForeColor: White
    TextAlign: MiddleLeft
           
    Label Account #:    
    MaskedTextBox   txtTenantAcntNbr Mask: 00-00-00
    Modifiers: Public
    Label Property #:    
    MaskedTextBox   txtPropertyCode Mask: 000-000
    Modifiers: Public
    Label Tenant Name    
    TextBox   txtTenantName Modifiers: Public
    Label Property Type:    
    TextBox   txtPropertyType Modifiers: Public
    Label Marital Status:    
    TextBox   txtMaritalStatus Modifiers: Public
    Label Monthly Rent:    
    TextBox   txtMonthlyRent  
    Label Allocation Evaluation   AutoSize: False
    BackColor: Gray
    BorderStyle: FixedSingle
    ForeColor: White
    TextAlign: MiddleLeft
    Label Contract Length:    
    ComboBox   cbxContractLength Items:
    Monthly
    3 Months
    6 Months
    12 Months
    Modifiers: Public
    Label Rent Start Date:    
    DateTimePicker   dtpRentStartDate Modifiers: Public
    Button OK btnOK DialogResult: OK
    Button Close btnClose DialogResult: Cancel
    Form     AcceptButton: btnOK
    CancelButton: btnClose
    FormBorderStyle: FixedDialog
    MaximizeBox: False
    MinimizeBox: False
    ShowInTaskbar: False
  31. Right-click the RentalAllocation form and click View Code
  32. Import the System.IO and the System.Xml namespaces:
     
    Imports System.IO
    Imports System.Xml
    
    Public Class RentalAllocation
    
    End Class
  33. In the Class Name combo box, select txtTenantAcntNbr
  34. In the Method Name combo box, select Leave and implement the event as follows: 
     
    Private Sub txtTenantAcntNbr_Leave(ByVal sender As Object, _
                                           ByVal e As System.EventArgs) _
                                           Handles txtTenantAcntNbr.Leave
        Dim Filename As String = "C:\Solas Property Rental\tenants.xml"
        Dim docTenants As XmlDocument = New XmlDocument
    
        If File.Exists(Filename) Then
            docTenants.Load(Filename)
            Dim TenantElement As XmlElement = docTenants.DocumentElement
            Dim ListOfTenants As XmlNodeList = TenantElement.ChildNodes
            Dim TenantFound As Boolean = False
    
            For i = 0 To ListOfTenants.Count - 1
                Dim Node As XmlNode = ListOfTenants(i)
    
                If Node.FirstChild.InnerText = txtTenantAcntNbr.Text Then
                    TenantFound = True
                    txtTenantName.Text = Node.FirstChild.NextSibling.InnerText
                    txtMaritalStatus.Text = Node.FirstChild.NextSibling.NextSibling.InnerText
                End If
            Next
    
            If TenantFound = False Then
                MsgBox("There is no tenant with that account number")
                txtTenantAcntNbr.Text = ""
            End If
        Else
            MsgBox("There is no list of tenants to check.")
        End If
    End Sub
  35. In the Class Name combo box, select txtPropertyCode
  36. In the Method Name combo box, select Leave and implement the event as follows: 
     
    Private Sub txtPropertyCode_Leave(ByVal sender As Object, _
                                      ByVal e As System.EventArgs) _
                                      Handles txtPropertyCode.Leave
        Dim Filename As String = "C:\Solas Property Rental\properties.xml"
        Dim DOMProperties As XmlDocument = New XmlDocument
    
        If File.Exists(Filename) Then
            DOMProperties.Load(Filename)
            Dim PropertyElement As XmlElement = DOMProperties.DocumentElement
            Dim ListOfProperties As XmlNodeList = PropertyElement.ChildNodes
            Dim PropertyFound As Boolean = False
    
            For i = 0 To ListOfProperties.Count - 1
                Dim Node As XmlNode = ListOfProperties(i)
    
                If Node.FirstChild.InnerText = txtPropertyCode.Text Then
                    PropertyFound = True
                    txtPropertyType.Text = Node.FirstChild.NextSibling.InnerText
                    txtMonthlyRent.Text = Node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.InnerText
                End If
            Next
    
            If PropertyFound = False Then
                MsgBox("There is no Property with that code")
                txtPropertyType.Text = ""
            End If
        Else
            MsgBox("There is no list of properties to check.")
        End If
    End Sub 
  37. To add a new form to the application, in the Solution Explorer, right-click SolasPropertyRental1 -> Add -> Windows Form...
  38. Set the Name to RentalAllocations and press Enter
  39. From the Toolbox, add a ListView to the form
  40. While the new list view is still selected, in the Properties window, click the ellipsis button of the Columns field and create the columns as follows:
     
    (Name) Text TextAlign Width
    colAllocationCode Alloc Code   65
    colDateAllocated Date Allocated Center 85
    colTenantAccount Tenant # Center 65
    colTenantName Tenant Name   100
    colPropertyCode Prop Code Center 65
    colPropertyType Prop Type   75
    colContractLength Contract Length   88
    colRentStartDate Rent Start Date Center 88
    colMonthlyRent Monthly Rent Right 76
  41. Design the form as follows: 
     
    Solas Property Rental: Rental Allocations
     
    Control Text Name Other Properties
    ListView   lvwAllocations View: Details
    GridLines: True
    FullRowSelect: True
    Anchor: Top, Bottom, Left, Right
    Button New Rental Allocation... btnNewAllocation Anchor: Bottom, Right
    Button Close btnClose  
  42. Right-click the Rental Allocations form and click View Code
  43. Import the System.IO and the System.Xml namespaces:
     
    Imports System.IO
    Imports System.Xml
    
    Public Class RentalAllocations
    
    End Class
  44. In the Class Name combo box, select txtTenantAcntNbr
  45. In the Method Name combo box, select Leave and implement the event as follows: 
     
    Private Sub ShowRentalAllocations()
        Dim Filename As String = "C:\Solas Property Rental\contracts.xml"
        Dim docAllocations As XmlDocument = New XmlDocument
    
        If File.Exists(Filename) Then
            lvwAllocations.Items.Clear()
    
            docAllocations.Load(Filename)
            Dim AllocationElement As XmlElement = docAllocations.DocumentElement
            Dim ListOfAllocations As XmlNodeList = AllocationElement.ChildNodes
    
            For Each Node As XmlNode In ListOfAllocations
                Dim lviAllocation As ListViewItem = New ListViewItem(Node.FirstChild.InnerText) ' Allocation Code
    
                lviAllocation.SubItems.Add(Node.FirstChild.NextSibling.InnerText) ' Date Allocated
                lviAllocation.SubItems.Add(Node.FirstChild.NextSibling.NextSibling.InnerText) ' Tenant Account Number
                lviAllocation.SubItems.Add(Node.FirstChild.NextSibling.NextSibling.NextSibling.InnerText) ' Tenant Name
                lviAllocation.SubItems.Add(Node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText) ' Property Code
                lviAllocation.SubItems.Add(Node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText) ' Property Type
                lviAllocation.SubItems.Add(Node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText) ' Contract Length
                lviAllocation.SubItems.Add(Node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText) ' Rent Start Date
                lviAllocation.SubItems.Add(Node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText) ' Monthly Rent
                lvwAllocations.Items.Add(lviAllocation)
            Next
        End If
    End Sub
  46. In the Class Name combo box, select (RentalAllocations Events)
  47. In the Method Name combo box, select Load and implement the event as follows:
     
    Private Sub RentalAllocations_Load(ByVal sender As Object, _
                                           ByVal e As System.EventArgs) _
                                           Handles Me.Load
        ShowRentalAllocations()
    End Sub
  48. To add a new form to the application, in the Solution Explorer, right-click SolasPropertyRental4 -> Add -> Windows Form...
  49. Set the Name to RentPayment and click Add
  50. Design the form as follows:
     
    Solas Property Rental: Rent Payment
    Control Text Name Other Properties
    Label Rent Allocation   AutoSize: False
    BackColor: Gray
    BorderStyle: FixedSingle
    ForeColor: White
    TextAlign: MiddleLeft
    Label Date Received:    
    DateTimePicker   dtpDateReceived Format: Short
    Modifiers: Public
    Label Allocation Code:    
    MaskedTextBox   txtAllocationCode Mask: 0000-9999
    Modifiers: Public
    Label Receipt #:    
    TextBox   txtReceiptNumber Modifiers: Public
    Label Tenant Account #:    
    TextBox   txtTenantAcntNber Modifiers: Public
    Label Property Code:    
    TextBox   txtPropertyCode Modifiers: Public
    Label Tenant Name:    
    TextBox   txtTenantName Modifiers: Public
    Label Property Type:    
    TextBox   txtPropertyType Modifiers: Public
    Label Payment Summary   AutoSize: False
    BackColor: Gray
    BorderStyle: FixedSingle
    ForeColor: White
    TextAlign: MiddleLeft
    Label Month:    
    Label Year:    
    Label Payment For:    
    ComboBox   cbxMonths Modifiers: Public
    Items:
    January
    February
    March
    April
    May
    June
    July
    August
    September
    October
    November
    December
    TextBox   txtYear Modifiers: Public
    Label Amount Received:    
    TextBox 0.00 txtAmountReceived TextAlign: Right
    Modifiers: Public
    Button OK btnOK DialogResult: OK
    Button Close btnClose DialogResult: Cancel
    Form     AcceptButton: btnOK
    CancelButton: btnClose
    FormBorderStyle: FixedDialog
    MaximizeBox: False
    MinimizeBox: False
    ShowInTaskbar: False
  51. Right-click the Rent Payment form and click View Code
  52. Import the System.IO and the System.Xml namespaces:
     
    Imports System.IO
    Imports System.Xml
    
    Public Class RentPayment
    
    End Class
  53. In the Class Name combo box, select txtAllocationCode
  54. In the Method Name combo box, select Leave and implement the event as follows: 
     
    Private Sub txtAllocationCode_Leave(ByVal sender As Object, _
                                        ByVal e As System.EventArgs) _
                                        Handles txtAllocationCode.Leave
        Dim Filename As String = "C:\Solas Property Rental\contracts.xml"
        Dim docAllocations As XmlDocument = New XmlDocument
    
        If File.Exists(Filename) Then
            docAllocations.Load(Filename)
            Dim AllocationElement As XmlElement = docAllocations.DocumentElement
            Dim ListOfAllocations As XmlNodeList = AllocationElement.ChildNodes
            Dim ContractFound As Boolean = False
    
            For i = 0 To ListOfAllocations.Count - 1
                Dim Node As XmlNode = ListOfAllocations(i)
    
                If Node.FirstChild.InnerText = txtAllocationCode.Text Then
                    ContractFound = True
                    txtTenantAcntNber.Text = Node.FirstChild.NextSibling.NextSibling.InnerText
                    txtTenantName.Text = Node.FirstChild.NextSibling.NextSibling.NextSibling.InnerText
                    txtPropertyCode.Text = Node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText
                    txtPropertyType.Text = Node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText
                    txtAmountReceived.Text = Node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText
                End If
            Next
    
            If ContractFound = False Then
                MsgBox("There is no rental contract with that number")
                txtTenantAcntNber.Text = ""
            End If
        Else
            MsgBox("There is no list of rental contracts to check.")
        End If
    End Sub
  55. To add a new form to the application, in the Solution Explorer, right- click SolasPropertyRental4 -> Add -> Windows Form...
  56. Set the Name to RentPayments and press Enter
  57. From the Toolbox, add a ListView to the form
  58. While the new list view is still selected, in the Properties window, click the ellipsis button of the Columns field and create the columns as follows:
     
    (Name) Text TextAlign Width
    colReceiptNumber Receipt # Right  
    colDateReceived Date Received Center 85
    colAllocationCode Alloc Code Center 65
    colTenantAccount Tenant # Center 65
    colTenantName Tenant Name   100
    colPropertyCode Prop Code Center 65
    colPropertyType Prop Type   75
    colPaymentFor Payment For   88
    colAmountReceived Amount Right 50
  59. Design the form as follows: 
     
    Solas Property Rental: Rent Payments
     
    Control Text Name Other Properties
    ListView   lvwRentPayments View: Details
    GridLines: True
    FullRowSelect: True
    Anchor: Top, Bottom, Left, Right
    Button New Rent Payment... btnNewPayment Anchor: Bottom,  Right
    Button Close btnClose Anchor: Bottom, Right
  60. Right-click the Rent Payments form and click View Code
  61. Import the System.IO and the System.Xml namespaces:
     
    Imports System.IO
    Imports System.Xml
    
    Public Class RentPayments
    
    End Class
  62. In the Class Name combo box, select txtTenantAcntNbr
  63. In the Method Name combo box, select Leave and implement the event as follows: 
     
    Private Sub ShowRentPayments()
        Dim Filename As String = "C:\Solas Property Rental\payments.xml"
        Dim DocumentPayments As XmlDocument = New XmlDocument
    
        If File.Exists(Filename) Then
            lvwRentPayments.Items.Clear()
    
            DocumentPayments.Load(Filename)
            Dim AllocationElement As XmlElement = DocumentPayments.DocumentElement
            Dim ListOfAllocations As XmlNodeList = AllocationElement.ChildNodes
    
            For Each Node As XmlNode In ListOfAllocations
                Dim lviPayment As ListViewItem = New ListViewItem(node.FirstChild.InnerText) ' Receipt Number
    
                lviPayment.SubItems.Add(node.FirstChild.NextSibling.InnerText) ' Date Received
                lviPayment.SubItems.Add(node.FirstChild.NextSibling.NextSibling.InnerText) ' Allocation Code
                lviPayment.SubItems.Add(node.FirstChild.NextSibling.NextSibling.NextSibling.InnerText) ' Tenant Account Number
                lviPayment.SubItems.Add(node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.InnerText)  ' Tenant Name
                lviPayment.SubItems.Add(node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText) ' Property Code
                lviPayment.SubItems.Add(node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText) ' Property Type
                lviPayment.SubItems.Add(node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText) ' Payment For
                lviPayment.SubItems.Add(node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText) ' Amount
                lvwRentPayments.Items.Add(lviPayment)
            Next
        End If
    End Sub
  64. In the Class Name combo box, select (RentPayments.Events)
  65. In the Method Name combo box, select Load and implement the event as follows:
     
    Private Sub RentPayments_Load(ByVal sender As Object, _
                                      ByVal e As System.EventArgs) _
                                      Handles Me.Load
        ShowRentPayments()
    End Sub
  66. In the Solution Explorer, right-click Form1.vb and click Rename
  67. Set the name to Central.vb and press Enter twice to display the form
  68. Design the form as follows:
     
    Solas Property Rental
    Control Text Name
    Button Tenants btnTenants
    Button Rental Properties btnRentalProperties
    Button Rental Allocations btnRentalAllocations
    Button C&lose btnClose
  69. Right-click the form and click View Code
  70. In the Class Name combo box, select btnRentPayment
  71. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnRentPayments_Click(ByVal sender As Object, _
                                      ByVal e As System.EventArgs) _
                                      Handles btnRentPayments.Click
        Dim frmPayment As RentPayments = New RentPayments
        frmPayment.Show()
    nd Sub   
  72. In the Class Name combo box, select btnRentalAllocations
  73. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnRentalAllocations_Click(ByVal sender As Object, _
                                           ByVal e As System.EventArgs) _
                                           Handles btnRentalAllocations.Click
        Dim frmAllocations As RentalAllocations = New RentalAllocations
        frmAllocations.ShowDialog()
    End Sub
  74. In the Class Name combo box, select btnTenants
  75. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnTenants_Click(ByVal sender As Object, _
                                 ByVal e As System.EventArgs) _
                                 Handles btnTenants.Click
        Dim frmTenants As Tenants = New Tenants
        frmTenants.ShowDialog()
    End Sub      
  76. In the Class Name combo box, select btnRentalProperties
  77. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnRentalProperties_Click(ByVal sender As Object, _
                                          ByVal e As System.EventArgs) _
                                          Handles btnRentalProperties.Click
        Dim frmProperties As RentalProperties = New RentalProperties
        frmProperties.ShowDialog()
    End Sub
  78. In the Class Name combo box, select btnClose
  79. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnClose_Click(ByVal sender As Object, _
                               ByVal e As System.EventArgs) _
                               Handles btnClose.Click
        End
    End Sub
  80. Save all

Appending an Element

To assist with in programmatically creating a new element, the XmlDocument class provides the CreateElement() method that is overloaded with three versions. One of the versions uses the following syntax:

Public Function CreateElement(name As String) As XmlElement

Using this method, to create a new element, call it and pass it the name of the element. For example, imagine you want to add a new Title element to the above file. You would start with code as follows:

Private Sub btnDocument_Click(ByVal sender As System.Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles btnDocument.Click
    Dim Filename As String = "videos.xml"
    Dim DOMDocument As XmlDocument = New XmlDocument

    If File.Exists(Filename) Then
        DOMDocument.Load(Filename)

        Dim NewElement As XmlElement = DOMDocument.CreateElement("Title")
    End If
End Sub

In order to add the new element to the file, you must specify its position in the tree: whether it would be the first or the last node, whether you want to position it before or after a node of your choice. For example, if you want to add a new Title element to the above file, it would be considered a child of the root, that is, a child of the XmlDocument.DocumentElement property. In the previous lesson, we learned how to get a reference to the root node.

To support the positions of existing nodes, the XmlNode class, which is the ancestor of all XML nodes of the .NET Framework, provides various appropriate methods. One of these methods is AppendChild(), which is used to add an element as the last child of its parent. The syntax of the XmlNode.AppendChild() method is:

Public Overridable Function AppendChild(newChild As XmlNode) As XmlNode

When calling this method, pass the XmlNode object you had previous created. After adding the node, if you want the file to keep it, you should save it. Here is an example:

Private Sub btnDocument_Click(ByVal sender As System.Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles btnDocument.Click
        Dim Filename As String = "videos.xml"
        Dim DOMDocument As XmlDocument = New XmlDocument

        If File.Exists(Filename) Then
            DOMDocument.Load(Filename)

            Dim RootElement As XmlElement = DOMDocument.DocumentElement
            Dim NewElement As XmlElement = DOMDocument.CreateElement("title")
            RootElement.AppendChild(NewElement)

            DOMDocument.Save(Filename)
        End If
End Sub

This would produce:

<?xml version="1.0" encoding="utf-8"?>
<videos>
  <title>The Distinguished Gentleman</title>
  <title />
</videos>

Notice that the newly added element is empty.

Adding the Inner Text of an Element

Suppose you have the following videos.xml file:

<?xml version="1.0" encoding="utf-8"?>
<videos>
  <video>
    <title>The Distinguished Gentleman</title>
    <director>Jonathan Lynn</director>
    <length>112 Minutes</length>
    <format>DVD</format>
    <rating>R</rating>
  </video>
  <video>
    <title>Her Alibi</title>
    <director>Bruce Beresford</director>
    <length>94 Minutes</length>
    <format>DVD</format>
    <rating>PG-13</rating>
  </video>
</videos>

Imagine that you want to add a video element. You have a choice of adding one, more than one, or all child elements of the video node. To perform this operation, one solution you can use is to "build" all child elements of the video element, then add the node as a whole.

In the previous lesson, we saw that the XmlNode.InnerXml property comprises a node, its markup, its children and their markup. This means that you can create the child node(s) with its (their) markup(s) as a string and assign that string to an XmlNode.InnerXml string. To do this, you would need the set version of the InnerXml property. It is declared as follows:

Public Overridable Property InnerXml As String

Here is an example that adds a complete new video node to the above XML file:

Private Sub btnDocument_Click(ByVal sender As System.Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles btnDocument.Click
    Dim Filename As String = "videos.xml"
    Dim DOMDocument As XmlDocument = New XmlDocument

    If File.Exists(Filename) Then
        DOMDocument.Load(Filename)

        Dim Element As XmlElement = DOMDocument.CreateElement("video")
        Dim strNewvideo As String = "<title>Other People's Money</title>" & _
                                    "<director>Alan Brunstein</director>" & _
                                    "<length>114 Minutes</length>" & _
                                    "<format>VHS</format>" & _
                                    "<rating>PG-13</rating>"

        Element.InnerXml = strNewvideo
        DOMDocument.DocumentElement.AppendChild(Element)

        DOMDocument.Save(Filename)
    End If
End Sub

This would produce:

<?xml version="1.0" encoding="utf-8"?>
<videos>
  <video>
    <title>The Distinguished Gentleman</title>
    <director>Jonathan Lynn</director>
    <length>112 Minutes</length>
    <format>DVD</format>
    <rating>R</rating>
  </video>
  <video>
    <title>Her Alibi</title>
    <director>Bruce Beresford</director>
    <length>94 Mins</length>
    <format>DVD</format>
    <rating>PG-13</rating>
  </video>
  <video>
    <title>Other People's Money</title>
    <director>Alan Brunstein</director>
    <length>114 Minutes</length>
    <format>VHS</format>
    <rating>PG-13</rating>
  </video>
</videos>

Practical Learning Practical Learning: Introducing operations on XML Elements

  1. In the Solution Explorer, right-click Tenants.vb and click View Code
  2. In the Class Name combo box, select btnNewTenant
  3. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnNewTenant_Click(ByVal sender As Object, _
                                       ByVal e As System.EventArgs) _
                                       Handles btnNewTenant.Click
            Dim AccountNumber As String
            Dim FullName As String
            Dim MaritalStatus As String
            Dim PhoneNumber As String
    
            ' If this directory doesn't exist, create it
            Directory.CreateDirectory("C:\Solas Property Rental")
            ' This is the XML file that holds the list of tenants
            Dim Filename As String = "C:\Solas Property Rental\tenants.xml"
            ' This is the dialog box from where a tenant is created
            Dim editor As TenantEditor = New TenantEditor
    
            ' Display the Tenant Editor Dialog and find out if the 
            ' user clicked OK after filling its controls
            If editor.ShowDialog() = DialogResult.OK Then
                ' We will need a reference to the XML document
                Dim DOMTenants As XmlDocument = New XmlDocument
    
                ' Find out if the file exists already
                ' If it doesn't, then create it
                If Not File.Exists(Filename) Then
                    DOMTenants.LoadXml("<?xml version=""1.0"" encoding=""utf-8""?>" & _
                                       "<Tenants></Tenants>")
                    DOMTenants.Save(Filename)
                End If
    
                ' At this time, we have a Tenants.xml file. Open it
                DOMTenants.Load(Filename)
    
                ' Get a reference to the root node
                Dim RootElement As XmlElement = DOMTenants.DocumentElement
    
                ' Prepare the values of the XML element
                AccountNumber = editor.txtAccountNumber.Text
                FullName = editor.txtFullName.Text
                MaritalStatus = editor.cbxMaritalStatus.Text
                PhoneNumber = editor.txtPhoneNumber.Text
    
                ' Create an element named Tenant
                Dim TenantElement As XmlElement = DOMTenants.CreateElement("Tenant")
                ' Create the XML code of the child element of Tenant
                Dim strTenant As String = "<AccountNumber>" & AccountNumber & _
                                          "</AccountNumber>" & _
                                          "<FullName>" & FullName & _
                                          "</FullName>" & _
                                          "<MaritalStatus>" & MaritalStatus & _
                                          "</MaritalStatus>" & _
                                          "<PhoneNumber>" & PhoneNumber & _
                                          "</PhoneNumber>"
                TenantElement.InnerXml = strTenant
                ' Append the new element as a child of Tenant
                DOMTenants.DocumentElement.AppendChild(TenantElement)
    
                ' Save the XML file
                DOMTenants.Save("C:\Solas Property Rental\tenants.xml")
                ' Since the content of the XML file has just been changed,
                ' re-display the list of tenants
                ShowTenants()
            End If
    End Sub
  4. In the Class Name combo box, select btnClose
  5. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnClose_Click(ByVal sender As Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles btnClose.Click
            Close()
    End Sub
  6. In the Solution Explorer, right-click RentalProperties.vb and click View Code
  7. In the Class Name combo box, select btnNewProperty
  8. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnNewProperty_Click(ByVal sender As Object, _
                                         ByVal e As System.EventArgs) _
                                         Handles btnNewProperty.Click
            ' If this directory doesn't exist, create it
            Directory.CreateDirectory("C:\Solas Property Rental")
            ' This is the XML file that holds the list of proeprties
            Dim Filename As String = "C:\Solas Property Rental\properties.xml"
            Dim Editor As PropertyEditor = New PropertyEditor
    
            Dim RandomNumber As Random = New Random
            Editor.txtPropertyCode.Text = RandomNumber.Next(100000, 999999)
    
            If Editor.ShowDialog() = DialogResult.OK Then
                Dim PropertyCode As String
                Dim PropertyType As String
                Dim Status As String
                Dim Bedrooms As Integer
                Dim Bathrooms As Single
                Dim MonthlyRent As Double
    
                ' We will need a reference to the XML document
                Dim docProperty As XmlDocument = New XmlDocument
    
                ' Find out if the file exists already
                ' If it doesn't, then create it
                If Not File.Exists(Filename) Then
                    docProperty.LoadXml("<?xml version=""1.0"" encoding=""utf-8""?>" & _
                                        "<Properties></Properties>")
                    docProperty.Save(Filename)
                End If
    
                ' Open the XML file
                docProperty.Load(Filename)
    
                ' Get a reference to the root node
                Dim RootElement As XmlElement = docProperty.DocumentElement
    
                PropertyCode = Editor.txtPropertyCode.Text
                PropertyType = Editor.cbxPropertyTypes.Text
                Bedrooms = CInt(Editor.txtBedrooms.Text)
                Bathrooms = CSng(Editor.txtBathrooms.Text)
                MonthlyRent = CDbl(Editor.txtMonthlyRent.Text)
                Status = Editor.cbxStatus.Text
    
                Dim PropertyElement As XmlElement = docProperty.CreateElement("Property")
                Dim strNewCustomer As String = "<PropertyCode>" & PropertyCode & _
                                        "</PropertyCode>" & "<PropertyType>" & _
                                        PropertyType & "</PropertyType>" & _
                                        "<Bedrooms>" & Bedrooms& "</Bedrooms>" & _
                                        "<Bathrooms>" & FormatNumber(Bathrooms) & _
                                        "</Bathrooms>" & "<MonthlyRent>" & _
                                        FormatNumber(MonthlyRent) & _
                                        "</MonthlyRent>" & _
                                        "<Status>" & Status & "</Status>"
    
                PropertyElement.InnerXml = strNewCustomer
                docProperty.DocumentElement.AppendChild(PropertyElement)
    
                docProperty.Save("C:\Solas Property Rental\properties.xml")
                ShowProperties()
            End If
    End Sub
  9. In the Class Name combo box, select btnClose
  10. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnClose_Click(ByVal sender As Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles btnClose.Click
            Close()
    End Sub
  11. Execute the application
  12. Use the Tenants button and its New Tenant button to create the following Tenants:
     
    Account # Full Name Marital Status Phone #
    20-48-46 Lenny Crandon Single (240) 975-9093
    57-97-15 Joan Ramey Married (301) 304-5845
    19-38-84 Peter Sellars Married (240) 801-7974
    24-68-84 Alberta Sanson Separated (202) 917-0095
    47-80-95 Urlus Flack Single (703) 203-7947
  13. Use the Rental Properties button and its New Property button to create the following properties:
     
    Prop Code Property Types Bedrooms Bathrooms Monthly Rent Status
    527-992 Apartment 1 1 925 Available
    726-454 Apartment 2 1 1150.5 Available
    476-473 Single Family 5 3.5 2250.85 Occupied
    625-936 Townhouse 3 2.5 1750 Available
    179-738 Townhouse 4 2.5 1920.5 Available
    727-768 Single Family 4 2.5 2140.5 Needs Repair
    371-801 Apartment 3 2 1250.25 Available
    241-536 Townhouse 3 1.5 1650.5 Occupied
     
  14. Close the forms and return to your programming environment

Adding an Element With Value

Consider the following XML file named videos.xml:

<?xml version="1.0" encoding="utf-8" ?>
<videos>
  <title>The Distinguished Gentleman</title>
</videos>

If you want the element to have a value, the XmlDocument class provides the CreateTextNode() method. This method returns an XmlText value. The syntax of this method is:

Public Overridable Function CreateTextNode(text As String) As XmlText

This method takes as argument the string that would constitute the value of the element. Before calling it, you should have used the XmlNode.AppendChild() method to create a node. Calling this method on the LastChild node of the one that called the AppendChild() would specify the value of the new node. Here is an example:

Private Sub btnDocument_Click(ByVal sender As System.Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles btnDocument.Click
        Dim Filename As String = "videos.xml"
        Dim DOMDocument As XmlDocument = New XmlDocument

        If File.Exists(Filename) Then
            DOMDocument.Load(Filename)
            Dim RootElement As XmlElement = DOMDocument.DocumentElement

            Dim ElementTitle As XmlElement = DOMDocument.CreateElement("title")
            Dim TextVideo As XmlText = DOMDocument.CreateTextNode("Basic Instinct")

            RootElement.AppendChild(ElementTitle)
            RootElement.LastChild.AppendChild(TextVideo)

            DOMDocument.Save(Filename)
        End If
End Sub

This would produce:

<?xml version="1.0" encoding="utf-8"?>
<videos>
  <title>The Distinguished Gentleman</title>
  <title>Basic Instinct</title>
</videos>

The combination of calls to XmlDocument.CreateElement() and XmlDocument.CreateTextNode() allow you to create a new element that has a value.

Consider the following XML file named "videos.xml":

<?xml version="1.0" encoding="utf-8"?>
<videos>
  <video>
    <title>The Distinguished Gentleman</title>
  </video>
  <video>
    <title>Basic Instinct</title>
  </video>
</videos>

Notice that the root, videos, has a repetitive child named video. This video child has its own child named Title. Imagine that you want to add a new video node that has a child. To do this, first create an empty video node as a child of the root. We learned earlier how to do that:

Private Sub btnDocument_Click(ByVal sender As System.Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles btnDocument.Click
        Dim Filename As String = "videos.xml"
        Dim DOMDocument As XmlDocument = New XmlDocument

        If File.Exists(Filename) Then
            DOMDocument.Load(Filename)

            Dim RootElement As XmlElement = DOMDocument.DocumentElement
            Dim Element As XmlElement = DOMDocument.CreateElement("video")
            RootElement.AppendChild(Element)
        End If
End Sub

After creating the new child of the root, initialize the grand child with the desired name (the name does not have to be one of the existing names) and a value (which is optional if you do not want the new node to have a value). Once the new node is ready, add it as the last child of the root. If this new node has a value, add its XmlText object as the LastChild of the LastChild of the root. Here is an example of how you would do this:

Private Sub btnDocument_Click(ByVal sender As System.Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles btnDocument.Click
        Dim Filename As String = "videos.xml"
        Dim DOMDocument As XmlDocument = New XmlDocument

        If File.Exists(Filename) Then
            DOMDocument.Load(Filename)

            Dim RootElement As XmlElement = DOMDocument.DocumentElement
            Dim Element As XmlElement = DOMDocument.CreateElement("video")
            RootElement.AppendChild(Element)

            RootElement = DOMDocument.DocumentElement

            Element = DOMDocument.CreateElement("title")
            Dim TextVideo As XmlText = DOMDocument.CreateTextNode("Her Alibi")

            RootElement.LastChild.AppendChild(Element)
            RootElement.LastChild.LastChild.AppendChild(TextVideo)

            DOMDocument.Save(Filename)
        End If
End Sub

This would produce:

<?xml version="1.0" encoding="utf-8"?>
<videos>
  <video>
    <title>The Distinguished Gentleman</title>
  </video>
  <video>
    <title>Basic Instinct</title>
  </video>
  <video>
    <title>Her Alibi</title>
  </video>
</videos>

Now consider the following file:

<?xml version="1.0" encoding="utf-8"?>
<videos>
  <video>
    <title>The Distinguished Gentleman</title>
    <director>Jonathan Lynn</director>
    <length>112 Minutes</length>
    <format>DVD</format>
    <rating>R</rating>
  </video>
  <video>
    <title>Her Alibi</title>
    <director>Bruce Beresford</director>
    <length>94 Minutes</length>
    <format>DVD</format>
    <rating>PG-13</rating>
  </video>
</videos>

The root, videos, has a child named video. The video node has many child nodes. By now, we know how to add a child to the root. We also saw how to add a grand child with value to the root. To had many (grand) children to a node, first build the node, add it to the root, then continuously add the necessary nodes, one at a time, including its name and its optional value. This would be done as follows:

Private Sub btnDocument_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              TenamHandles btnDocument.Click
    Dim Filename As String = "videos.xml"
    Dim DOMDocument As XmlDocument = New XmlDocument

    If File.Exists(Filename) Then
        DOMDocument.Load(Filename)

        Dim RootElement As XmlElement = DOMDocument.DocumentElement
        Dim Element As XmlElement = DOMDocument.CreateElement("video")
        RootElement.AppendChild(Element)

        RootElement = DOMDocument.DocumentElement

        Element = DOMDocument.CreateElement("title")
        Dim TextVideo As XmlText = DOMDocument.CreateTextNode("The Day After Tomorrow")
        RootElement.LastChild.AppendChild(Element)
        RootElement.LastChild.LastChild.AppendChild(TextVideo)

        Element = DOMDocument.CreateElement("director")
        TextVideo = DOMDocument.CreateTextNode("Roland Emmerich")
        RootElement.LastChild.AppendChild(Element)
        RootElement.LastChild.LastChild.AppendChild(TextVideo)

        Element = DOMDocument.CreateElement("length")
        TextVideo = DOMDocument.CreateTextNode("124 Minutes")
        RootElement.LastChild.AppendChild(Element)
        RootElement.LastChild.LastChild.AppendChild(TextVideo)

        Element = DOMDocument.CreateElement("format")
        TextVideo = DOMDocument.CreateTextNode("DVD")
        RootElement.LastChild.AppendChild(Element)
        RootElement.LastChild.LastChild.AppendChild(TextVideo)

        Element = DOMDocument.CreateElement("rating")
        TextVideo = DOMDocument.CreateTextNode("PG-13")
        RootElement.LastChild.AppendChild(Element)
        RootElement.LastChild.LastChild.AppendChild(TextVideo)

        DOMDocument.Save(Filename)
    End If
End Sub

 This would produce:

<?xml version="1.0" encoding="utf-8"?>
<videos>
  <video>
    <title>The Distinguished Gentleman</title>
    <director>Jonathan Lynn</director>
    <length>112 Minutes</length>
    <format>DVD</format>
    <rating>R</rating>
  </video>
  <video>
    <title>Her Alibi</title>
    <director>Bruce Beresford</director>
    <length>94 Minutes</length>
    <format>DVD</format>
    <rating>PG-13</rating>
  </video>
  <video>
    <title>The Day After Tomorrow</title>
    <director>Roland Emmerich</director>
    <length>124 Minutes</length>
    <format>DVD</format>
    <rating>PG-13</rating>
  </video>
</videos>

Using the same approach, you can add children to children of children, and so on.

 

Practical LearningPractical Learning: Programmatically Adding an Element

  1. In the Solution Explorer, right-click RentalAllocations.vb and click View Code
  2. In the Class Name combo box, select btnNewAllocation
  3. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnNewAllocation_Click(ByVal sender As Object, _
                                           ByVal e As System.EventArgs) _
                                           Handles btnNewAllocation.Click
        Dim AllocationCode As String
        Dim TenantAccountNumber As String
        Dim TenantName As String
        Dim MaritalStatus As String
        Dim PropertyCode As String
        Dim PropertyType As String
        Dim ContractLength As String
        Dim DateAllocated As DateTime
        Dim RentStartDate As Date
        Dim MonthlyRent As Double
    
        Dim Editor As RentalAllocation = New RentalAllocation
        Directory.CreateDirectory("C:\Solas Property Rental")
        Dim Filename As String = "C:\Solas Property Rental\contracts.xml"
    
        If Editor.ShowDialog() = DialogResult.OK Then
            Dim DOMAllocation As XmlDocument = New XmlDocument
    
            If Not File.Exists(Filename) Then
                DOMAllocation.LoadXml( _
    		"<?xml version=""1.0"" encoding=""utf-8""?>" & _
                    "<Allocations></Allocations>")
                DOMAllocation.Save(Filename)
            End If
    
            DOMAllocation.Load(Filename)
    
            Dim RootElement As XmlElement = DOMAllocation.DocumentElement
    
            AllocationCode = Editor.txtAllocationCode.Text
            DateAllocated = Editor.dtpDateAllocated.Value
            TenantAccountNumber = Editor.txtTenantAcntNbr.Text
            TenantName = Editor.txtTenantName.Text
            MaritalStatus = Editor.txtMaritalStatus.Text
            PropertyCode = Editor.txtPropertyCode.Text
            PropertyType = Editor.txtPropertyType.Text
            MonthlyRent = CDbl(Editor.txtMonthlyRent.Text)
            ContractLength = Editor.cbxContractLengths.Text
            RentStartDate = Editor.dtpRentStartDate.Value
    
            Dim RootElement As XmlElement = DOMAllocation.DocumentElement
            Dim AllocationElement As XmlElement = _
    		DOMAllocation.CreateElement("RentalAllocation")
            RootElement.AppendChild(AllocationElement)
    
            RootElement = DOMAllocation.DocumentElement
    
            AllocationElement = DOMAllocation.CreateElement("AllocationCode")
            Dim txtAllocation As XmlText = _
    		DOMAllocation.CreateTextNode(AllocationCode)
            RootElement.LastChild.AppendChild(AllocationElement)
            RootElement.LastChild.LastChild.AppendChild(txtAllocation)
    
            AllocationElement = DOMAllocation.CreateElement("DateAllocated")
            txtAllocation = _
    		DOMAllocation.CreateTextNode(DateAllocated.ToString("d"))
            RootElement.LastChild.AppendChild(AllocationElement)
            RootElement.LastChild.LastChild.AppendChild(txtAllocation)
    
            AllocationElement = _
    		DOMAllocation.CreateElement("TenantAccountNumber")
            txtAllocation = _
    		DOMAllocation.CreateTextNode(TenantAccountNumber)
            RootElement.LastChild.AppendChild(AllocationElement)
            RootElement.LastChild.LastChild.AppendChild(txtAllocation)
    
            AllocationElement = DOMAllocation.CreateElement("TenantName")
            txtAllocation = DOMAllocation.CreateTextNode(TenantName)
            RootElement.LastChild.AppendChild(AllocationElement)
            RootElement.LastChild.LastChild.AppendChild(txtAllocation)
    
            AllocationElement = DOMAllocation.CreateElement("MaritalStatus")
            txtAllocation = DOMAllocation.CreateTextNode(MaritalStatus)
            RootElement.LastChild.AppendChild(AllocationElement)
            RootElement.LastChild.LastChild.AppendChild(txtAllocation)
    
            AllocationElement = DOMAllocation.CreateElement("PropertyCode")
            txtAllocation = DOMAllocation.CreateTextNode(PropertyCode)
            RootElement.LastChild.AppendChild(AllocationElement)
            RootElement.LastChild.LastChild.AppendChild(txtAllocation)
    
            AllocationElement = DOMAllocation.CreateElement("PropertyType")
            txtAllocation = DOMAllocation.CreateTextNode(PropertyType)
            RootElement.LastChild.AppendChild(AllocationElement)
            RootElement.LastChild.LastChild.AppendChild(txtAllocation)
    
            AllocationElement = DOMAllocation.CreateElement("ContractLength")
            txtAllocation = DOMAllocation.CreateTextNode(ContractLength)
            RootElement.LastChild.AppendChild(AllocationElement)
            RootElement.LastChild.LastChild.AppendChild(txtAllocation)
    
            AllocationElement = DOMAllocation.CreateElement("RentStartDate")
            txtAllocation = _
    		DOMAllocation.CreateTextNode(RentStartDate.ToString("d"))
            RootElement.LastChild.AppendChild(AllocationElement)
            RootElement.LastChild.LastChild.AppendChild(txtAllocation)
    
            AllocationElement = DOMAllocation.CreateElement("MonthlyRent")
            txtAllocation = _
    		DOMAllocation.CreateTextNode(FormatNumber(MonthlyRent))
            RootElement.LastChild.AppendChild(AllocationElement)
            RootElement.LastChild.LastChild.AppendChild(txtAllocation)
    
            DOMAllocation.Save(Filename)
            ShowRentalAllocations()
        End If
    End Sub
  4. In the Class Name combo box, select btnClose
  5. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnClose_Click(ByVal sender As Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles btnClose.Click
        Close()
    End Sub
  6. In the Solution Explorer, right-click RentPayments.vb and click View Code
  7. In the Class Name combo box, select btnRentPayment
  8. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnNewPayment_Click(ByVal sender As Object, _
                                        ByVal e As System.EventArgs) _
                                        Handles btnNewPayment.Click
            Dim ReceiptNumber As Integer
            Dim AllocationCode As String
            Dim TenantAccountNumber As String
            Dim TenantName As String
            Dim PaymentFor As String
            Dim PropertyCode As String
            Dim PropertyType As String
            Dim DateReceived As DateTime
            Dim AmountReceived As Double
    
            Dim Editor As RentPayment = New RentPayment
            Dim DOMPayment As XmlDocument = New XmlDocument
            Directory.CreateDirectory("C:\Solas Property Rental")
            Dim Filename As String = "C:\Solas Property Rental\payments.xml"
    
            ' If some payments were previously made
            If File.Exists(Filename) Then
                ' Open the payments.xml file
                DOMPayment.Load(Filename)
    
                ' Locate the root element
                Dim AllocationElement As XmlElement = DOMPayment.DocumentElement
                ' Get a list of the child nodes
                Dim ListOfAllocations As XmlNodeList = AllocationElement.ChildNodes
    
                ' Get the last receipt number
                ReceiptNumber = _
                    CInt(ListOfAllocations(ListOfAllocations.Count _
                                            - 1).FirstChild.InnerText) + 1
    
                Editor.txtReceiptNumber.Text = ReceiptNumber.ToString()
            Else
                ' If no payment has ever been made,
                ' create a new XML file for the payments
                DOMPayment.LoadXml("<?xml version=""1.0"" encoding=""utf-8""?>" & _
                                   "<RentPayments></RentPayments>")
    
                ' We will start the receipt numbers at 101
                ReceiptNumber = 101
    
                Editor.txtReceiptNumber.Text = ReceiptNumber
            End If
    
            ' Display the Rent Payment dialog box
            If Editor.ShowDialog() = DialogResult.OK Then
                ' If the user had clicked OK,
                ' Prepare the elements of the XML file
                ReceiptNumber = CInt(Editor.txtReceiptNumber.Text)
                DateReceived = Editor.dtpDateReceived.Value
                AllocationCode = Editor.txtAllocationCode.Text
                TenantAccountNumber = Editor.txtTenantAcntNber.Text
                TenantName = Editor.txtTenantName.Text
                PropertyCode = Editor.txtPropertyCode.Text
                PropertyType = Editor.txtPropertyType.Text
                PaymentFor = Editor.cbxMonths.Text & " " & Editor.txtYear.Text
                AmountReceived = CDbl(Editor.txtAmountReceived.Text)
    
                ' Get a reference to the root element
                Dim RootElement As XmlElement = DOMPayment.DocumentElement
                ' Create an element named Payment
                Dim PaymentElement As XmlElement = DOMPayment.CreateElement("Payment")
                ' Add the new element as the last node of the root element
                RootElement.AppendChild(PaymentElement)
    
                ' Get a reference to the root element
                RootElement = DOMPayment.DocumentElement
    
                ' Create an element
                PaymentElement = DOMPayment.CreateElement("ReceiptNumber")
                ' Create the value of the new element
                Dim TextPayment As XmlText = DOMPayment.CreateTextNode(ReceiptNumber)
                ' Add the new element as a child of the Payment element
                RootElement.LastChild.AppendChild(PaymentElement)
                ' Specify the value of the new element
                RootElement.LastChild.LastChild.AppendChild(TextPayment)
    
                ' Follow the same logic for the other elements
    
                PaymentElement = DOMPayment.CreateElement("DateReceived")
                TextPayment = DOMPayment.CreateTextNode(DateReceived.ToString("d"))
                RootElement.LastChild.AppendChild(PaymentElement)
                RootElement.LastChild.LastChild.AppendChild(TextPayment)
    
                PaymentElement = DOMPayment.CreateElement("AllocationCode")
                Dim TextAllocation As XmlText = DOMPayment.CreateTextNode(AllocationCode)
                RootElement.LastChild.AppendChild(PaymentElement)
                RootElement.LastChild.LastChild.AppendChild(TextAllocation)
    
                PaymentElement = DOMPayment.CreateElement("TenantAccountNumber")
                TextAllocation = DOMPayment.CreateTextNode(TenantAccountNumber)
                RootElement.LastChild.AppendChild(PaymentElement)
                RootElement.LastChild.LastChild.AppendChild(TextAllocation)
    
                PaymentElement = DOMPayment.CreateElement("TenantName")
                TextAllocation = DOMPayment.CreateTextNode(TenantName)
                RootElement.LastChild.AppendChild(PaymentElement)
                RootElement.LastChild.LastChild.AppendChild(TextAllocation)
    
                PaymentElement = DOMPayment.CreateElement("PropertyCode")
                TextAllocation = DOMPayment.CreateTextNode(PropertyCode)
                RootElement.LastChild.AppendChild(PaymentElement)
                RootElement.LastChild.LastChild.AppendChild(TextAllocation)
    
                PaymentElement = DOMPayment.CreateElement("PropertyType")
                TextAllocation = DOMPayment.CreateTextNode(PropertyType)
                RootElement.LastChild.AppendChild(PaymentElement)
                RootElement.LastChild.LastChild.AppendChild(TextAllocation)
    
                PaymentElement = DOMPayment.CreateElement("PaymentFor")
                TextAllocation = DOMPayment.CreateTextNode(PaymentFor)
                RootElement.LastChild.AppendChild(PaymentElement)
                RootElement.LastChild.LastChild.AppendChild(TextAllocation)
    
                PaymentElement = DOMPayment.CreateElement("AmountReceived")
                TextAllocation = DOMPayment.CreateTextNode(FormatNumber(AmountReceived))
                RootElement.LastChild.AppendChild(PaymentElement)
                RootElement.LastChild.LastChild.AppendChild(TextAllocation)
    
                DOMPayment.Save(Filename)
                ShowRentPayments()
            End If
    End Sub
  9. In the Class Name combo box, select btnClose
  10. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnClose_Click(ByVal sender As Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles btnClose.Click
        Close()
    End Sub
  11. Execute the application
  12. Create the following Rental Allocations:
     
      Allocation 1 Allocation 2 Allocation 3 Allocation 4
    Allocation Code 4205-8274 5920-9417 2792-4075 7957-7294
    Date Allocated 8/12/2002 2/18/2004 3/24/2004 10/26/2007
    Account # 24-68-84 57-97-15 19-38-84 20-48-46
    Prop Code 726-454 625-936 371-801 727-768
    Contract Length 12 Months 3 Months 12 Months 6 Months
    Start Date 10/1/2002 4/1/2004 6/1/2004 2/1/2008
     
    Solas Property Rental
    Solas Property Rental
  13. Create the following Rent Payments:
     
      Date Received Allocation Code Payment For Amount
    Month Year
    Payment 1 10/25/2002 4205-8274 October 2002 1150.50
    Payment 2 11/28/2002 4205-8274 November 2002 1150.50
    Payment 3 4/28/2004 5920-9417 April 2004 1750.00
    Payment 4 7/5/2004 2792-4075 June 2004 1250.25
    Payment 5 6/3/2004 5920-9417 May 2004 1750.00
    Payment 6 7/30/2004 2792-4075 July 2004 1250.25
    Payment 7 7/5/2004 5920-9417 June 2004 1750.00
    Payment 8 12/30/2002 4205-8274 December 2002 1150.50
     
    Solas Property Rental
  14. Close the DOS window
 

Exercises

 

Solas Property Rental

  1. Open the Solas Property Rental database from this lesson
  2. Configure the Rental Allocations form so that, after the user has entered a property code and pressed Tab (or when the control looses focus), the database will first check the status of the property. If the property is occupied, a message box will be displayed to the user and that particular property cannot be selected (the property code text box should be set empty)
  3. Configure the Rent Payments so that the user can decide to see only the payments for one particular tenant (you can create a contextual menu so that if the user right-clicks a certain row and click View Tenant's Payments, the list view would display only that tenant's payments. Of course, make sure the user has a way to display all payments again)

Previous Copyright 2008, Yevol Next