Home

Maintenance of XML Elements

 

Locating an Element

 

Introduction

In some cases, you may want to perform an operation on an existing and particular node. For example, you may want to change the value of a node, you may want to add a new child node to an existing node, etc. Before taking any of these actions, you must be able to locate or identify the desired element.

Locating an element consists of looking for a particular node among the nodes. To do this, you must start somewhere. Obviously, the first node you can identify is the root. Once you get the root, you can then get a collection of its children. After getting a collection of the child nodes of the root, you can locate a node in the collection. If the node you are looking for is a child of that first collection, you can then get a collection of the child nodes of that node and proceed.

Fortunately, the System.Xml namespace provides various means of looking for a node in an XML document.

Practical Learning: Introducing Element Location 

  1. Start Microsoft Visual Basic and create a Windows Forms Application named GeorgetownDryCleaner2
  2. In the Solution Explorer, right-click Form1.vb and click Rename
  3. Type Central.vb and press Enter
  4. Design the form as follows:
     
    Georgetown Cleaning Services
     
    Control Name Text Additional Properties
    GroupBox GroupBox   Order Identification  
    Label Label   &Receipt #:  
    TextBox TextBox txtReceiptNumber 1000 TextAlign: Right
    Button Button btnOpen Open  
    Button Button btnNewCleaningOrder New Cleaning Order  
    Label Label   Customer Name:  
    TextBox TextBox txtCustomerName    
    Label Label   Customer Phone:  
    MaskedTextBox TextBox txtCustomerPhone   Mask: (999) 000-0000
    Label Label   Date Left:  
    DateTimePicker DateTimePicker dtpDateLeft    
    Label Label   Time Left:  
    DateTimePicker Date Time Picker dtpTimeLeft   Format: Time
    Label Label   Date Expected:  
    DateTimePicker DateTimePicker dtpDateExpected    
    Label Label   Time Expected:  
    DateTimePicker DateTimePicker dtpTimeExpected   Format: Time
    Label Label   Order &Status:  
    ComboBox ComboBox cbxOrderStatus    
    Label Label   D&ate Picked Up:  
    DateTimePicker DateTimePicker dtpDatePickedUp    
    Label Label   Time Pic&kep Up:  
    DateTimePicker DateTimePicker dtpTimePickedUp    
    GroupBox GroupBox   Order Processing  
    Label Label   Item Type  
    Label Label   Unit Price  
    Label Label   Qty  
    Label Label   Sub Total  
    Label Label   Shirts  
    TextBox TextBox txtUnitPriceShirts 1.25 TextAlign: Right
    TextBox TextBox txtQuantityShirts 0 TextAlign: Right
    TextBox TextBox txtSubTotalShirts 0.00 TextAlign: Right
    Label Label   Pants  
    TextBox TextBox txtUnitPricePants 1.95 TextAlign: Right
    TextBox TextBox txtQuantityPants   TextAlign: Right
    TextBox TextBox txtSubTotalPants 0.00 TextAlign: Right
    ComboBox ComboBox cbxNameItem1 None Items:
    None
    Women Suit
    Dress
    Regular Skirt
    Skirt With Hook
    Men's Suit 2Pc
    Men's Suit 3Pc
    Sweaters
    Silk Shirt
    Tie
    Coat
    Jacket
    Swede
    TextBox TextBox txtUnitPriceItem1 0.00 TextAlign: Right
    TextBox TextBox txtQuantityItem1 0 TextAlign: Right
    TextBox TextBox txtSubTotalItem1 0.00 TextAlign: Right
    ComboBox ComboBox cbxNameItem2 None Items:
    None
    Women Suit
    Dress
    Regular Skirt
    Skirt With Hook
    Men's Suit 2Pc
    Men's Suit 3Pc
    Sweaters
    Silk Shirt
    Tie
    Coat
    Jacket
    Swede
    TextBox TextBox txtUnitPriceItem2 0.00 TextAlign: Right
    TextBox TextBox txtQuantityItem2 0 TextAlign: Right
    TextBox TextBox txtSubTotalItem2 0.00 TextAlign: Right
    ComboBox ComboBox cbxNameItem3 None Items:
    None
    Women Suit
    Dress
    Regular Skirt
    Skirt With Hook
    Men's Suit 2Pc
    Men's Suit 3Pc
    Sweaters
    Silk Shirt
    Tie
    Coat
    Jacket
    Swede
    TextBox TextBox txtUnitPriceItem3 0.00 TextAlign: Right
    TextBox TextBox txtQuantityItem3 0 TextAlign: Right
    TextBox TextBox txtSubTotalItem3 0.00 TextAlign: Right
    ComboBox ComboBox cbxNameItem4 None Items:
    None
    Women Suit
    Dress
    Regular Skirt
    Skirt With Hook
    Men's Suit 2Pc
    Men's Suit 3Pc
    Sweaters
    Silk Shirt
    Tie
    Coat
    Jacket
    Swede
    TextBox TextBox txtUnitPriceItem4 0.00 TextAlign: Right
    TextBox TextBox txtQuantityItem4 0 TextAlign: Right
    TextBox TextBox txtSubTotalItem4 0.00 TextAlign: Right
    GroupBox GroupBox   Order Summary  
    Label Label   Cleaning Total:  
    TextBox TextBox txtCleaningTotal 0.00 TextAlign: Right
    Label Label   Tax Rate:  
    TextBox TextBox txtTaxRate 7.75 TextAlign: Right
    Label Label   %  
    Label Label   Tax Amount:  
    TextBox TextBox txtTaxAmount 0.00 TextAlign: Right
    Label Label   Net Total:  
    TextBox TextBox txtNetPrice 0.00 TextAlign: Right
    Button Button btnPrint Print...  
    Button Button btnPrintPreview Print Preview...  
    Button Button btnClose Close  
  5. Double-click the Time Left control and implement its ValueChanged event as follows:
     
    Imports System.IO
    Imports System.Xml
    
    Public Class Central
    
        Private Sub dtpTimeLeft_ValueChanged(ByVal sender As System.Object, _
                                             ByVal e As System.EventArgs) _
                                             Handles dtpTimeLeft.ValueChanged
            Dim DateLeft As Date = dtpDateLeft.Value
            Dim TimeLeft As Date = dtpTimeLeft.Value
    
            Dim Time9AM As Date = New DateTime(TimeLeft.Year, _
                                               TimeLeft.Month, _
                                               TimeLeft.Day, 9, 0, 0)
    
            ' If the customer leaves clothes before 9AM...
            If TimeLeft <= Time9AM Then
                ' ... then they should be ready the same day after 5PM
                dtpDateExpected.Value = DateLeft
                dtpTimeExpected.Value = New DateTime(DateLeft.Year, _
                                                     DateLeft.Month, _
                                                     DateLeft.Day, 17, 0, 0)
            Else
                ' If the clothes were left after 9AM,
                ' then they will be available
                ' the following business morning at 8AM
                ' If the following day is Sunday,
                ' then they will be ready the following Monday
                If DateLeft.DayOfWeek = DayOfWeek.Saturday Then
                    dtpDateExpected.Value = DateLeft.AddDays(2D)
                    dtpTimeExpected.Value = New DateTime(DateLeft.Year, _
                                                         DateLeft.Month, _
                                                         DateLeft.Day + 2, 8, 0, 0)
                Else
                    dtpDateExpected.Value = New DateTime(DateLeft.Year, _
                                                         DateLeft.Month, _
                                                         DateLeft.Day + 1)
                    dtpTimeExpected.Value = New DateTime(DateLeft.Year, _
                                                         DateLeft.Month, _
                                                         DateLeft.Day + 1, 8, 0, 0)
                End If
            End If
        End Sub
    End Sub
  6. Return to the form  
  7. From the Printing section of the Toolbox, click PrintDocument and click the form
  8. While the new control is still selected, in the Properties window, click the Properties button, click (Name), type docPrint and press Enter
  9. Under the form, double-click docPrint and implement its event as follows:
     
    Private Sub docPrint_PrintPage(ByVal sender As System.Object, _
                       ByVal e As System.Drawing.Printing.PrintPageEventArgs) _
                                   Handles docPrint.PrintPage
            e.Graphics.DrawLine(New Pen(Color.Black, 2), 60, 90, 720, 90)
            e.Graphics.DrawLine(New Pen(Color.Black, 1), 60, 93, 720, 93)
    
            Dim strDisplay As String = "Georgetown Dry Cleaner"
            Dim fntString As System.Drawing.Font = _
                    New Font("Times New Roman", 28, _
                        FontStyle.Bold)
            e.Graphics.DrawString(strDisplay, fntString, _
                        Brushes.Black, 120, 100)
    
            strDisplay = "Customer Cleaning Order"
            fntString = New System.Drawing.Font("Times New Roman", 18, _
                        FontStyle.Bold)
            e.Graphics.DrawString(strDisplay, fntString, _
                        Brushes.Black, 220, 150)
    
            e.Graphics.DrawLine(New Pen(Color.Black, 1), 60, 184, 720, 184)
            e.Graphics.DrawLine(New Pen(Color.Black, 2), 60, 188, 720, 188)
    
            fntString = New System.Drawing.Font("Times New Roman", 12, _
                        FontStyle.Bold)
            e.Graphics.DrawString("", fntString, _
                        Brushes.Black, 80, 200)
    
            fntString = New System.Drawing.Font("Times New Roman", 12, _
                        FontStyle.Bold)
            e.Graphics.DrawString("Customer Identification:  ", fntString, _
                        Brushes.Black, 100, 220)
            fntString = New System.Drawing.Font("Times New Roman", 12, _
                        FontStyle.Regular)
            e.Graphics.DrawString(txtCustomerName.Text & "  -  " & _
                                          txtCustomerPhone.Text, fntString, _
                                          Brushes.Black, 300, 220)
    
            e.Graphics.DrawLine(New Pen(Color.Black, 1), 100, 240, 700, 240)
    
            fntString = New Font("Times New Roman", 12, FontStyle.Bold)
            e.Graphics.DrawString("Date Left:        ", fntString, _
                                          Brushes.Black, 100, 260)
            fntString = New Font("Times New Roman", 12, FontStyle.Regular)
    
            e.Graphics.DrawString(dtpDateLeft.Value.ToString("D"), fntString, _
                                          Brushes.Black, 300, 260)
            e.Graphics.DrawLine(New Pen(Color.Black, 1), 100, 280, 700, 280)
    
            fntString = New Font("Times New Roman", 12, FontStyle.Bold)
            e.Graphics.DrawString("Time Left: ", fntString, _
                                          Brushes.Black, 500, 260)
            fntString = New Font("Times New Roman", 12, FontStyle.Regular)
            e.Graphics.DrawString(dtpTimeLeft.Value.ToString("t"), fntString, _
                                          Brushes.Black, 620, 260)
    
            fntString = New System.Drawing.Font("Times New Roman", _
             12, FontStyle.Bold)
            e.Graphics.DrawString("Date Expected:    ", fntString, _
                        Brushes.Black, 100, 300)
            fntString = New Font("Times New Roman", 12, FontStyle.Regular)
            e.Graphics.DrawString(dtpDateExpected.Value.ToString("D"), _
             fntString, Brushes.Black, 300, 300)
    
            fntString = New Font("Times New Roman", 12, FontStyle.Bold)
            e.Graphics.DrawString("Time Expected: ", fntString, _
                                          Brushes.Black, 500, 300)
            fntString = New Font("Times New Roman", 12, FontStyle.Regular)
            e.Graphics.DrawString(dtpTimeExpected.Value.ToString("t"), _
             fntString, Brushes.Black, 620, 300)
    
            e.Graphics.DrawLine(New Pen(Color.Black, 2), 100, 320, 700, 320)
    
            fntString = New Font("Times New Roman", 12, FontStyle.Bold)
            e.Graphics.DrawString("Item Type", _
                                      fntString, Brushes.Black, 140, 350)
            e.Graphics.DrawString("Unit Price", _
                                      fntString, Brushes.Black, 300, 350)
            e.Graphics.DrawString("Quantity", _
                                      fntString, Brushes.Black, 405, 350)
            e.Graphics.DrawString("Sub-Total", _
                                      fntString, Brushes.Black, 500, 350)
    
            e.Graphics.DrawLine(New Pen(Color.Black, 2), 140, 370, 640, 370)
    
            Dim fmtString As StringFormat = New StringFormat
            fmtString.Alignment = StringAlignment.Far
    
            e.Graphics.DrawString("Shirts", _
                                      fntString, Brushes.Black, 150, 380)
            fntString = New Font("Times New Roman", 12, FontStyle.Regular)
            e.Graphics.DrawString(txtUnitPriceShirts.Text, fntString, _
                        Brushes.Black, 350, 380, fmtString)
            e.Graphics.DrawString(txtQuantityShirts.Text, fntString, _
                        Brushes.Black, 440, 380, fmtString)
            e.Graphics.DrawString(txtSubTotalShirts.Text, fntString, _
                        Brushes.Black, 550, 380, fmtString)
            e.Graphics.DrawLine(New Pen(Color.Black, 1), 140, 400, 640, 400)
    
            fntString = New Font("Times New Roman", 12, FontStyle.Bold)
            e.Graphics.DrawString("Pants", _
                                          fntString, Brushes.Black, 150, 410)
            fntString = New Font("Times New Roman", 12, FontStyle.Regular)
            e.Graphics.DrawString(txtUnitPricePants.Text, fntString, _
                        Brushes.Black, 350, 410, fmtString)
            e.Graphics.DrawString(txtQuantityPants.Text, fntString, _
                        Brushes.Black, 440, 410, fmtString)
            e.Graphics.DrawString(txtSubTotalPants.Text, fntString, _
                        Brushes.Black, 550, 410, fmtString)
            e.Graphics.DrawLine(New Pen(Color.Black, 1), 140, 430, 640, 430)
    
            fntString = New Font("Times New Roman", 12, FontStyle.Bold)
            e.Graphics.DrawString(cbxNameItem1.Text, _
                                          fntString, Brushes.Black, 150, 440)
            fntString = New Font("Times New Roman", 12, FontStyle.Regular)
            e.Graphics.DrawString(txtUnitPriceItem1.Text, fntString, _
                        Brushes.Black, 350, 440, fmtString)
            e.Graphics.DrawString(txtQuantityItem1.Text, fntString, _
                        Brushes.Black, 440, 440, fmtString)
            e.Graphics.DrawString(txtSubTotalItem1.Text, fntString, _
                        Brushes.Black, 550, 440, fmtString)
            e.Graphics.DrawLine(New Pen(Color.Black, 1), 140, 460, 640, 460)
    
            fntString = New Font("Times New Roman", 12, FontStyle.Bold)
            e.Graphics.DrawString(cbxNameItem2.Text, _
                                          fntString, Brushes.Black, 150, 470)
            fntString = New Font("Times New Roman", 12, FontStyle.Regular)
            e.Graphics.DrawString(txtUnitPriceItem2.Text, fntString, _
                        Brushes.Black, 350, 470, fmtString)
            e.Graphics.DrawString(txtQuantityItem2.Text, fntString, _
                        Brushes.Black, 440, 470, fmtString)
            e.Graphics.DrawString(txtSubTotalItem2.Text, fntString, _
                        Brushes.Black, 550, 470, fmtString)
            e.Graphics.DrawLine(New Pen(Color.Black, 1), 140, 490, 640, 490)
    
            fntString = New Font("Times New Roman", 12, FontStyle.Bold)
            e.Graphics.DrawString(cbxNameItem3.Text, _
                                          fntString, Brushes.Black, 150, 500)
            fntString = New Font("Times New Roman", 12, FontStyle.Regular)
            e.Graphics.DrawString(txtUnitPriceItem3.Text, fntString, _
                        Brushes.Black, 350, 500, fmtString)
            e.Graphics.DrawString(txtQuantityItem3.Text, fntString, _
                        Brushes.Black, 440, 500, fmtString)
            e.Graphics.DrawString(txtSubTotalItem3.Text, fntString, _
                        Brushes.Black, 550, 500, fmtString)
            e.Graphics.DrawLine(New Pen(Color.Black, 1), 140, 520, 640, 520)
    
            fntString = New Font("Times New Roman", 12, FontStyle.Bold)
            e.Graphics.DrawString(cbxNameItem4.Text, _
                        fntString, Brushes.Black, 150, 530)
            fntString = New Font("Times New Roman", 12, FontStyle.Regular)
            e.Graphics.DrawString(txtUnitPriceItem4.Text, fntString, _
                        Brushes.Black, 350, 530, fmtString)
            e.Graphics.DrawString(txtQuantityItem4.Text, fntString, _
                        Brushes.Black, 440, 530, fmtString)
            e.Graphics.DrawString(txtSubTotalItem4.Text, fntString, _
                        Brushes.Black, 550, 530, fmtString)
            e.Graphics.DrawLine(New Pen(Color.Black, 2), 140, 550, 640, 550)
    
            fntString = New System.Drawing.Font("Times New Roman", 12, _
             FontStyle.Bold)
            e.Graphics.DrawString("Order Summary", fntString, _
                                  Brushes.Black, 260, 600)
            e.Graphics.DrawLine(New Pen(Color.Black, 2), 220, 620, 560, 620)
    
            fntString = New System.Drawing.Font("Times New Roman", _
             10, FontStyle.Bold)
            e.Graphics.DrawString("Cleaning Total:", fntString, _
                                  Brushes.Black, 260, 630)
            fntString = New System.Drawing.Font("Times New Roman", _
             10, FontStyle.Regular)
            e.Graphics.DrawString(txtCleaningTotal.Text, fntString, _
                                  Brushes.Black, 440, 630, fmtString)
            e.Graphics.DrawLine(New Pen(Color.Black, 1), _
           220, 650, 520, 650)
    
            fntString = New System.Drawing.Font("Times New Roman", _
             10, FontStyle.Bold)
            e.Graphics.DrawString("Tax Rate:", fntString, _
                                  Brushes.Black, 260, 660)
            fntString = New System.Drawing.Font("Times New Roman", _
             10, FontStyle.Regular)
            e.Graphics.DrawString(txtTaxRate.Text, fntString, _
                                  Brushes.Black, 440, 660, fmtString)
            e.Graphics.DrawLine(New Pen(Color.Black, 1), _
           220, 680, 520, 680)
    
            fntString = New System.Drawing.Font("Times New Roman", _
             10, FontStyle.Bold)
            e.Graphics.DrawString("Tax Amount:", fntString, _
                                  Brushes.Black, 260, 690)
            fntString = New System.Drawing.Font("Times New Roman", _
             10, FontStyle.Regular)
            e.Graphics.DrawString(txtTaxAmount.Text, fntString, _
                           Brushes.Black, 440, 690, fmtString)
            e.Graphics.DrawLine(New Pen(Color.Black, 1), _
           220, 710, 520, 710)
    
            fntString = New System.Drawing.Font("Times New Roman", _
             10, FontStyle.Bold)
            e.Graphics.DrawString("Net Price:", fntString, _
                        Brushes.Black, 260, 720)
            fntString = New System.Drawing.Font("Times New Roman", _
             10, FontStyle.Regular)
            e.Graphics.DrawString(txtNetPrice.Text, fntString, _
                        Brushes.Black, 440, 720, fmtString)
            e.Graphics.DrawLine(New Pen(Color.Black, 2), _
           200, 740, 560, 740)
    End Sub
  10. Return to the form
  11. From the Printing section of the Toolbox, click PrintDialog and click the form
  12. In the Properties window, change its Name to dlgPrint
  13. Still in the Properties windows, set its Document property to docPrint
  14. On the form, double-click the Print button and implement the event as follows:
     
    Private Sub btnPrint_Click(ByVal sender As System.Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles btnPrint.Click
            If dlgPrint.ShowDialog() = DialogResult.OK Then
                docPrint.Print()
            End If
    End Sub
  15. Return to the form
  16. From the Printing section of the Toolbox, click PrintPreviewDialog and click the form
  17. In the Properties window, change its Name to dlgPrintPreview
  18. Still in the Properties windows, set its Document property to docPrint
  19. On the form, double-click File the btnPrintPreview button and implement the event as follows:
     
    Private Sub btnPrintPreview_Click(ByVal sender As System.Object, _
                                          ByVal e As System.EventArgs) _
                                          Handles btnPrintPreview.Click
            dlgPrintPreview.ShowDialog()
    End Sub
  20. Save the file

Locating an Element Using its Index

Consider the following XML file named videos.xml:

<?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>
    <video>
	<title>Other People's Money</title>
	<director>Alan Brunstein</director>
	<length>114 Minutes</length>
	<format>VHS</format>
	<rating>PG-13</rating>
    </video>
</videos>

In Lesson 8, we saw that the XmlNodeList class was equipped with both a method named Item and an indexed property (named Item). Their syntaxes are:

Public MustOverride Function Item(index As Integer) As XmlNode
Property Item(index As Integer) As XmlNode

These two members allow you to access an element based on its index. Here are examples:

Imports System.Xml
Imports System.IO

Public Class Exercise
    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 ListOfVideos As XmlNodeList = RootElement.ChildNodes

            MsgBox(ListOfVideos(1).InnerText)
            MsgBox(ListOfVideos.Item(3).InnerXml)
        End If
    End Sub
End Class

This would produce:

 

 

 

Videos

Videos

You can use this characteristic to locate a node. Because XML is very flexible with the names (you can have two child nodes that have the same name) and values (you can have two child nodes that have the same value) of nodes, when creating an XML document, it is your responsibility to create a scheme that would eventually allow you to uniquely identify each element.

Practical Learning: Locating an Element Using its Index

  1. In the Class Name combo box, select btnNewCleaningOrder
  2. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnNewCleaningOrder_Click(ByVal sender As Object, _
                                              ByVal e As System.EventArgs) _
                                              Handles btnNewCleaningOrder.Click
            Dim ReceiptNumber As Integer = 1000
            Dim DOMCleaningOrders As XmlDocument = New XmlDocument
            Directory.CreateDirectory("C:\Georgetown Dry Cleaner")
            Dim Filename As String = _
                        "C:\Georgetown Dry Cleaner\cleaningorders.xml"
    
            ' If some payments were previously made
            If File.Exists(Filename) Then
                ' Open the payments.xml file
                DOMCleaningOrders.Load(Filename)
    
                ' Locate the root element
                Dim CleaningOrderElement As XmlElement = _
                        DOMCleaningOrders.DocumentElement
                ' Get a list of the child nodes
                Dim ListOfCleaningOrders As XmlNodeList = _
                        CleaningOrderElement.ChildNodes
    
                ' Get the last student number
                ReceiptNumber = _
                    CInt(ListOfCleaningOrders(ListOfCleaningOrders.Count _
                                                   - 1).FirstChild.InnerText)
            End If
    
            txtReceiptNumber.Text = CStr(ReceiptNumber + 1)
    
            txtCustomerName.Text = ""
            txtCustomerPhone.Text = ""
            dtpDateLeft.Value = DateTime.Today
            dtpTimeLeft.Value = DateTime.Today
            dtpDateExpected.Value = DateTime.Today
            dtpTimeExpected.Value = DateTime.Today
    
            cbxOrderStatus.Text = "Not Yet Ready"
            dtpDatePickedUp.Value = DateTime.Today
            dtpTimePickedUp.Value = DateTime.Today
    
            txtUnitPriceShirts.Text = "1.25"
            txtQuantityShirts.Text = "0"
            txtSubTotalShirts.Text = "0.00"
            txtUnitPricePants.Text = "1.95"
            txtQuantityPants.Text = "0"
            txtSubTotalPants.Text = "0.00"
            cbxNameItem1.Text = "None"
            txtUnitPriceItem1.Text = "0.00"
            txtQuantityItem1.Text = "0"
            txtSubTotalItem1.Text = "0.00"
            cbxNameItem2.Text = "None"
            txtUnitPriceItem2.Text = "0.00"
            txtQuantityItem2.Text = "0"
            txtSubTotalItem2.Text = "0.00"
            cbxNameItem3.Text = "None"
            txtUnitPriceItem3.Text = "0.00"
            txtQuantityItem3.Text = "0"
            txtSubTotalItem3.Text = "0.00"
            cbxNameItem4.Text = "None"
            txtUnitPriceItem4.Text = "0.00"
            txtQuantityItem4.Text = "0"
            txtSubTotalItem4.Text = "0.00"
    
            txtCleaningTotal.Text = "0.00"
            txtTaxRate.Text = "7.75"
            txtTaxAmount.Text = "0.00"
            txtCleaningTotal.Text = "0.00"
    
            txtCustomerName.Focus()
    End Sub
  3. In the Class Name combo box, select (Central Events)
  4. In the Method Name combo box, select Load and implement the event as follows:
     
    Private Sub Central_Load(ByVal sender As Object, _
                                 ByVal e As System.EventArgs) _
                                 Handles Me.Load
        btnNewCleaningOrder_Click(sender, e)
    End Sub
  5. Save the file

Locating an Element Using its Name

To assist you with locating the first child node of a node, the XmlNode class is equipped with an indexed property (named Item) overloaded with two versions. One of the versions is declared as follows:

Public Overridable ReadOnly Property Item(name As String) As XmlElement

This indexed property takes the name of a node as argument. After the property has been called, the parser checks the child nodes of the element on which the property was applied. If the parser finds a node with that name, it returns it as an XmlElement object. 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 ListOfVideos As XmlNodeList = RootElement.ChildNodes

            MsgBox(ListOfVideos(1)("director").InnerText)
            MsgBox(ListOfVideos.Item(3)("format").InnerXml)
        End If
End Sub

Based on the videos.xml file we had earlier, this would produce:

Videos Videos

If the node has more than one child with the same name, then it would return the first child with that name. You can use this characteristic to look for, or locate, an element.

Practical Learning: Locating an Element Using its Name

  1. In the Class Name combo box, select btnOpen
  2. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnOpen_Click(ByVal sender As Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles btnOpen.Click
            Dim Filename As String = _
                        "C:\Georgetown Dry Cleaner\cleaningorders.xml"
            Dim DOMCleaningOrders As XmlDocument = New XmlDocument
    
            If File.Exists(Filename) Then
                Dim Found As Boolean = False
                DOMCleaningOrders.Load(Filename)
                Dim CleaningOrderElement As XmlElement = _
                            DOMCleaningOrders.DocumentElement
                Dim ListOfCleaningOrders As XmlNodeList = _
                            CleaningOrderElement.ChildNodes
    
                For i As Integer = 0 To ListOfCleaningOrders.Count - 1
                    If ListOfCleaningOrders(i).FirstChild.InnerText = _
                        txtReceiptNumber.Text Then
                        found = True
    
                        txtCustomerName.Text = _
                            ListOfCleaningOrders(i)("CustomerName").InnerText
                        txtCustomerPhone.Text = _
                            ListOfCleaningOrders(i)("CustomerPhone").InnerText
                        dtpDateLeft.Value = _
                            DateTime.Parse(ListOfCleaningOrders(i)("DateLeft").InnerText)
                        dtpTimeLeft.Value = _
                            DateTime.Parse(ListOfCleaningOrders(i)("TimeLeft").InnerText)
                        dtpDateExpected.Value = _
                            DateTime.Parse(ListOfCleaningOrders(i)("DateExpected").InnerText)
                        dtpTimeExpected.Value = _
                            DateTime.Parse(ListOfCleaningOrders(i)("TimeExpected").InnerText)
    
                        cbxOrderStatus.Text = _
                            ListOfCleaningOrders(i)("OrderStatus").InnerText
                        dtpDatePickedUp.Value = _
                            DateTime.Parse(ListOfCleaningOrders(i)("DatePickedUp").InnerText)
                        dtpTimePickedUp.Value = _
                            DateTime.Parse(ListOfCleaningOrders(i)("TimePickedUp").InnerText)
    
                        txtUnitPriceShirts.Text = _
                            ListOfCleaningOrders(i)("UnitPriceShirts").InnerText
                        txtQuantityShirts.Text = _
                            ListOfCleaningOrders(i)("QuantityShirts").InnerText
                        txtSubTotalShirts.Text = _
                            ListOfCleaningOrders(i)("SubTotalShirts").InnerText
                        txtUnitPricePants.Text = _
                            ListOfCleaningOrders(i)("UnitPricePants").InnerText
                        txtQuantityPants.Text = _
                            ListOfCleaningOrders(i)("QuantityPants").InnerText
                        txtSubTotalPants.Text = _
                            ListOfCleaningOrders(i)("SubTotalPants").InnerText
    
                        cbxNameItem1.Text = ListOfCleaningOrders(i)("NameItem1").InnerText
                        txtUnitPriceItem1.Text = _
                            ListOfCleaningOrders(i)("UnitPriceItem1").InnerText
                        txtQuantityItem1.Text = _
                            ListOfCleaningOrders(i)("QuantityItem1").InnerText
                        txtSubTotalItem1.Text = _
                            ListOfCleaningOrders(i)("SubTotalItem1").InnerText
    
                        cbxNameItem2.Text = ListOfCleaningOrders(i)("NameItem2").InnerText
                        txtUnitPriceItem2.Text = _
                        ListOfCleaningOrders(i)("UnitPriceItem2").InnerText
                        txtQuantityItem2.Text = _
                            ListOfCleaningOrders(i)("QuantityItem2").InnerText
                        txtSubTotalItem2.Text = _
                            ListOfCleaningOrders(i)("SubTotalItem2").InnerText
    
                        cbxNameItem3.Text = ListOfCleaningOrders(i)("NameItem3").InnerText
                        txtUnitPriceItem3.Text = _
                            ListOfCleaningOrders(i)("UnitPriceItem3").InnerText
                        txtQuantityItem3.Text = _
                            ListOfCleaningOrders(i)("QuantityItem3").InnerText
                        txtSubTotalItem3.Text = _
                            ListOfCleaningOrders(i)("SubTotalItem3").InnerText
    
                        cbxNameItem4.Text = ListOfCleaningOrders(i)("NameItem4").InnerText
                        txtUnitPriceItem4.Text = _
                            ListOfCleaningOrders(i)("UnitPriceItem4").InnerText
                        txtQuantityItem4.Text = _
                            ListOfCleaningOrders(i)("QuantityItem4").InnerText
                        txtSubTotalItem4.Text = _
                            ListOfCleaningOrders(i)("SubTotalItem4").InnerText
    
                        txtCleaningTotal.Text = _
                            ListOfCleaningOrders(i)("CleaningTotal").InnerText
                        txtTaxRate.Text = ListOfCleaningOrders(i)("TaxRate").InnerText
                        txtTaxAmount.Text = ListOfCleaningOrders(i)("TaxAmount").InnerText
                        txtNetPrice.Text = ListOfCleaningOrders(i)("NetPrice").InnerText
                        Exit For
                    End If
                Next
    
                If Found = False Then
                    MsgBox("There is no cleaning order with that receipt number")
                End If
            Else
                MsgBox("There is no file that holds the list of cleaning orders")
            End If
    End Sub
  3. Under the above End Sub line, create the following procedure:
     
    Private Sub SaveCleaningOrder()
            ' This variable will be used to know
            ' if the receipt number already exists in the file
            Dim ReceiptFound As Boolean = False
    
            ' This variable will be used to know whether we are creating
            ' a new cleaning order or if we are only updating
            ' an existing cleaning order
            Dim ExistingCleaningOrder As XmlNode = Nothing
    
            Dim ReceiptNumber As Integer = CInt(txtReceiptNumber.Text)
            ' We will need a reference to the DOM
            Dim DOMCleaningOrders As XmlDocument = New XmlDocument
            ' Here is the XML file that holds the cleaning orders
            Dim Filename As String = _
                        "C:\Georgetown Dry Cleaner\cleaningorders.xml"
    
            ' If there is no receipt number, don't do anything
            If txtReceiptNumber.Text.Length = 0 Then
                MsgBox("The cleaning order cannot be created " & _
                                "because the receipt number is missing")
                Exit Sub
            End If
    
            ' If the file exists,...
            If File.Exists(Filename) Then
                ' then open it
                DOMCleaningOrders.Load(Filename)
                Dim CleaningOrderElement As XmlElement = DOMCleaningOrders.DocumentElement
                Dim ListOfCleaningOrders As XmlNodeList = CleaningOrderElement.ChildNodes
    
                For i As Integer = 0 To ListOfCleaningOrders.Count - 1
                    Dim Node As XmlNode = ListOfCleaningOrders.Item(i)
    
                    If ListOfCleaningOrders.Item(i).FirstChild.InnerText = _
                        txtReceiptNumber.Text Then
                        ReceiptFound = True
                        ExistingCleaningOrder = ListOfCleaningOrders(i)
                        ReceiptNumber = _
                            CInt(ExistingCleaningOrder("ReceiptNumber").InnerText)
                        Exit For
                    End If
                Next
    
                If ReceiptFound = True Then
                    ExistingCleaningOrder("CustomerName").InnerText = _
                                txtCustomerName.Text
                    ExistingCleaningOrder("CustomerPhone").InnerText = _
                                txtCustomerPhone.Text
    
                    ExistingCleaningOrder("DateLeft").InnerText = _
                                dtpDateLeft.Value.ToString("d")
                    ExistingCleaningOrder("TimeLeft").InnerText = _
                                dtpTimeLeft.Value.ToString("t")
                    ExistingCleaningOrder("DateExpected").InnerText = _
                                dtpDateExpected.Value.ToString("d")
                    ExistingCleaningOrder("TimeExpected").InnerText = _
                        dtpTimeExpected.Value.ToString("t")
    
                    ExistingCleaningOrder("OrderStatus").InnerText = _
                        cbxOrderStatus.Text
                    ExistingCleaningOrder("DatePickedUp").InnerText = _
                        dtpDatePickedUp.Value.ToString("d")
                    ExistingCleaningOrder("TimePickedUp").InnerText = _
                        dtpTimePickedUp.Value.ToString("t")
    
                    ExistingCleaningOrder("UnitPriceShirts").InnerText = _
                        txtUnitPriceShirts.Text
                    ExistingCleaningOrder("QuantityShirts").InnerText = _
                        txtQuantityShirts.Text
                    ExistingCleaningOrder("SubTotalShirts").InnerText = _
                        txtSubTotalShirts.Text
    
                    ExistingCleaningOrder("UnitPricePants").InnerText = _
                        txtUnitPricePants.Text
                    ExistingCleaningOrder("QuantityPants").InnerText = _
                        txtQuantityPants.Text
                    ExistingCleaningOrder("SubTotalPants").InnerText = _
                        txtSubTotalPants.Text
    
                    ExistingCleaningOrder("NameItem1").InnerText = cbxNameItem1.Text
                    ExistingCleaningOrder("UnitPriceItem1").InnerText = _
                        txtUnitPriceItem1.Text
                    ExistingCleaningOrder("QuantityItem1").InnerText = _
                        txtQuantityItem1.Text
                    ExistingCleaningOrder("SubTotalItem1").InnerText = _
                        txtSubTotalItem1.Text
    
                    ExistingCleaningOrder("NameItem2").InnerText = cbxNameItem2.Text
                    ExistingCleaningOrder("UnitPriceItem2").InnerText = _
                        txtUnitPriceItem2.Text
                    ExistingCleaningOrder("QuantityItem2").InnerText = _
                        txtQuantityItem2.Text
                    ExistingCleaningOrder("SubTotalItem2").InnerText = _
                        txtSubTotalItem2.Text
    
                    ExistingCleaningOrder("NameItem3").InnerText = cbxNameItem3.Text
                    ExistingCleaningOrder("UnitPriceItem3").InnerText = _
                        txtUnitPriceItem3.Text
                    ExistingCleaningOrder("QuantityItem3").InnerText = _
                        txtQuantityItem3.Text
                    ExistingCleaningOrder("SubTotalItem3").InnerText = _
                        txtSubTotalItem3.Text
    
                    ExistingCleaningOrder("NameItem4").InnerText = _
                        cbxNameItem4.Text
                    ExistingCleaningOrder("UnitPriceItem4").InnerText = _
                        txtUnitPriceItem4.Text
                    ExistingCleaningOrder("QuantityItem4").InnerText = _
                        txtQuantityItem4.Text
                    ExistingCleaningOrder("SubTotalItem4").InnerText = _
                        txtSubTotalItem4.Text
    
                    ExistingCleaningOrder("CleaningTotal").InnerText = _
                        txtCleaningTotal.Text
                    ExistingCleaningOrder("TaxRate").InnerText = _
                        txtTaxRate.Text
                    ExistingCleaningOrder("TaxAmount").InnerText = _
                        txtTaxAmount.Text
                    ExistingCleaningOrder("NetPrice").InnerText = _
                        txtNetPrice.Text
                Else ' The receipt number was not found. So, create a new cleaning order
                    Dim RootElement As XmlElement = DOMCleaningOrders.DocumentElement
                    Dim NewElement As XmlElement = _
                         DOMCleaningOrders.CreateElement("CleaningOrder")
    
                    Dim strNewCleaningOrder As String = _
                         "<ReceiptNumber>" & txtReceiptNumber.Text & _
                         "</ReceiptNumber>" & "<CustomerName>" & _
                         txtCustomerName.Text & "</CustomerName>" & _
                         "<CustomerPhone>" & txtCustomerPhone.Text & _
                         "</CustomerPhone>" & "<DateLeft>" & _
                         dtpDateLeft.Value.ToString("d") & "</DateLeft>" & _
                         "<TimeLeft>" & dtpTimeLeft.Value.ToString("t") & _
                         "</TimeLeft>" & "<DateExpected>" & _
                         dtpDateExpected.Value.ToString("d") & _
                         "</DateExpected>" & "<TimeExpected>" & _
                         dtpTimeExpected.Value.ToString("t") & _
                         "</TimeExpected>" & "<OrderStatus>" & _
                         cbxOrderStatus.Text & "</OrderStatus>" & _
                         "<DatePickedUp>" & dtpDatePickedUp.Value.ToString("d") & _
                         "</DatePickedUp>" & "<TimePickedUp>" & _
                         dtpTimePickedUp.Value.ToString("t") & _
                         "</TimePickedUp>" & "<UnitPriceShirts>" & _
                         txtUnitPriceShirts.Text & "</UnitPriceShirts>" & _
                         "<QuantityShirts>" & txtQuantityShirts.Text & _
                         "</QuantityShirts>" & "<SubTotalShirts>" & _
                         txtSubTotalShirts.Text & "</SubTotalShirts>" & _
                         "<UnitPricePants>" & txtUnitPricePants.Text & _
                         "</UnitPricePants>" & "<QuantityPants>" & _
                         txtQuantityPants.Text & "</QuantityPants>" & _
                         "<SubTotalPants>" & txtSubTotalPants.Text & _
                         "</SubTotalPants>" & "<NameItem1>" & _
                         cbxNameItem1.Text & "</NameItem1>" & _
                         "<UnitPriceItem1>" & txtUnitPriceItem1.Text & _
                         "</UnitPriceItem1>" & "<QuantityItem1>" & _
                         txtQuantityItem1.Text & "</QuantityItem1>" & _
                         "<SubTotalItem1>" & txtSubTotalItem1.Text & _
                         "</SubTotalItem1>" & "<NameItem2>" & _
                         cbxNameItem2.Text & "</NameItem2>" & _
                         "<UnitPriceItem2>" & txtUnitPriceItem2.Text & _
                         "</UnitPriceItem2>" & "<QuantityItem2>" & _
                         txtQuantityItem2.Text & "</QuantityItem2>" & _
                         "<SubTotalItem2>" & txtSubTotalItem2.Text & _
                         "</SubTotalItem2>" & "<NameItem3>" & _
                         cbxNameItem3.Text & "</NameItem3>" & _
                         "<UnitPriceItem3>" & txtUnitPriceItem3.Text & _
                         "</UnitPriceItem3>" & "<QuantityItem3>" & _
                         txtQuantityItem3.Text & "</QuantityItem3>" & _
                         "<SubTotalItem3>" & txtSubTotalItem3.Text & _
                         "</SubTotalItem3>" & "<NameItem4>" & _
                         cbxNameItem4.Text & "</NameItem4>" & _
                         "<UnitPriceItem4>" & txtUnitPriceItem4.Text & _
                         "</UnitPriceItem4>" & "<QuantityItem4>" & _
                         txtQuantityItem4.Text & "</QuantityItem4>" & _
                         "<SubTotalItem4>" & txtSubTotalItem4.Text & _
                         "</SubTotalItem4>" & "<CleaningTotal>" & _
                         txtCleaningTotal.Text & "</CleaningTotal>" & _
                         "<TaxRate>" & txtTaxRate.Text & "</TaxRate>" & _
                         "<TaxAmount>" & txtTaxAmount.Text & "</TaxAmount>" & _
                         "<NetPrice>" & txtNetPrice.Text & "</NetPrice>"
    
                    NewElement.InnerXml = strNewCleaningOrder
                    DOMCleaningOrders.DocumentElement.AppendChild(NewElement)
                End If
    
                ' DOMCleaningOrders.Save(strFilename)
                ' If there is no such a file, prepare to create it
            Else REM if NOT File.Exists(strFilename))
                DOMCleaningOrders.LoadXml("<?xml version=""1.0"" encoding=""utf-8""?>" & _
                                          "<CleaningOrders></CleaningOrders>")
    
                Dim RootElement As XmlElement = DOMCleaningOrders.DocumentElement
                Dim CleaningOrderElement As XmlElement = DOMCleaningOrders.CreateElement("CleaningOrder")
                Dim strNewCleaningOrder As String = _
                        "<ReceiptNumber>" & txtReceiptNumber.Text & _
                        "</ReceiptNumber>" & "<CustomerName>" & _
                        txtCustomerName.Text & "</CustomerName>" & _
                        "<CustomerPhone>" & txtCustomerPhone.Text & _
                        "</CustomerPhone>" & "<DateLeft>" & _
                        dtpDateLeft.Value.ToString("d") & "</DateLeft>" & _
                        "<TimeLeft>" & dtpTimeLeft.Value.ToString("t") & _
                        "</TimeLeft>" & "<DateExpected>" & _
                        dtpDateExpected.Value.ToString("d") & _
                        "</DateExpected>" & "<TimeExpected>" & _
                        dtpTimeExpected.Value.ToString("t") & _
                        "</TimeExpected>" & "<OrderStatus>" & _
                        cbxOrderStatus.Text & "</OrderStatus>" & _
                        "<DatePickedUp>" & dtpDatePickedUp.Value.ToString("d") & _
                        "</DatePickedUp>" & "<TimePickedUp>" & _
                        dtpTimePickedUp.Value.ToString("t") & _
                        "</TimePickedUp>" & "<UnitPriceShirts>" & _
                        txtUnitPriceShirts.Text & "</UnitPriceShirts>" & _
                        "<QuantityShirts>" & txtQuantityShirts.Text & _
                        "</QuantityShirts>" & "<SubTotalShirts>" & _
                        txtSubTotalShirts.Text & "</SubTotalShirts>" & _
                        "<UnitPricePants>" & txtUnitPricePants.Text & _
                        "</UnitPricePants>" & "<QuantityPants>" & _
                        txtQuantityPants.Text & "</QuantityPants>" & _
                        "<SubTotalPants>" & txtSubTotalPants.Text & _
                        "</SubTotalPants>" & "<NameItem1>" & _
                        cbxNameItem1.Text & "</NameItem1>" & _
                        "<UnitPriceItem1>" & txtUnitPriceItem1.Text & _
                        "</UnitPriceItem1>" & "<QuantityItem1>" & _
                        txtQuantityItem1.Text & "</QuantityItem1>" & _
                        "<SubTotalItem1>" & txtSubTotalItem1.Text & _
                        "</SubTotalItem1>" & "<NameItem2>" & _
                        cbxNameItem2.Text & "</NameItem2>" & _
                        "<UnitPriceItem2>" & txtUnitPriceItem2.Text & _
                        "</UnitPriceItem2>" & "<QuantityItem2>" & _
                        txtQuantityItem2.Text & "</QuantityItem2>" & _
                        "<SubTotalItem2>" & txtSubTotalItem2.Text & _
                        "</SubTotalItem2>" & "<NameItem3>" & _
                        cbxNameItem3.Text & "</NameItem3>" & _
                        "<UnitPriceItem3>" & txtUnitPriceItem3.Text & _
                        "</UnitPriceItem3>" & "<QuantityItem3>" & _
                        txtQuantityItem3.Text & "</QuantityItem3>" & _
                        "<SubTotalItem3>" & txtSubTotalItem3.Text & _
                        "</SubTotalItem3>" & "<Item4Name>" & _
                        cbxNameItem4.Text & "</Item4Name>" & _
                        "<UnitPriceItem4>" & txtUnitPriceItem4.Text & _
                        "</UnitPriceItem4>" & "<QuantityItem4>" & _
                        txtQuantityItem4.Text & "</QuantityItem4>" & _
                        "<SubTotalItem4>" & txtSubTotalItem4.Text & _
                        "</SubTotalItem4>" & "<CleaningTotal>" & _
                        txtCleaningTotal.Text & "</CleaningTotal>" & _
                        "<TaxRate>" & txtTaxRate.Text & "</TaxRate>" & _
                        "<TaxAmount>" & txtTaxAmount.Text & "</TaxAmount>" & _
                        "<NetPrice>" & txtNetPrice.Text & "</NetPrice>"
    
                CleaningOrderElement.InnerXml = strNewCleaningOrder
                DOMCleaningOrders.DocumentElement.AppendChild(CleaningOrderElement)
            End If
    
            DOMCleaningOrders.Save(Filename)
    End Sub
  4. Under the above End Sub line, implement the following event:
     
    Private Sub ControlLeave(ByVal sender As Object, _
                                 ByVal e As EventArgs) _
                                 Handles txtUnitPriceShirts.Leave, _
                                         txtQuantityShirts.Leave, _
                                         txtUnitPricePants.Leave, _
                                         txtQuantityPants.Leave, _
                                         txtUnitPriceShirts.Leave, _
                                         txtQuantityPants.Leave, _
                                         txtUnitPriceItem1.Leave, _
                                         txtQuantityItem1.Leave, _
                                         txtUnitPriceItem2.Leave, _
                                         txtQuantityItem2.Leave, _
                                         txtUnitPriceItem3.Leave, _
                                         txtQuantityItem3.Leave, _
                                         txtUnitPriceItem4.Leave, _
                                         txtQuantityItem4.Leave, _
                                         txtTaxRate.Leave
            Dim UnitPriceShirts As Double, UnitPricePants As Double
            Dim UnitPriceItem1 As Double, UnitPriceItem2 As Double
            Dim UnitPriceItem3 As Double, UnitPriceItem4 As Double
            Dim SubTotalShirts As Double, SubTotalPants As Double
            Dim SubTotalItem1 As Double, SubTotalItem2 As Double
            Dim SubTotalItem3 As Double, SubTotalItem4 As Double
            Dim QuantityShirts As Integer = 1, QuantityPants As Integer = 1
            Dim QuantityItem1 As Integer = 1
            Dim QuantityItem2 As Integer = 1, QuantityItem3 As Integer = 1
            Dim QuantityItem4 As Integer = 4
            Dim CleaningTotal As Double = 0.0, TaxRate As Double
            Dim TaxAmount As Double = 0.0, NetPrice As Double
    
            ' Retrieve the unit price of this item
            ' Just in case the user types an invalid value,
            ' we are using a try...catch
            Try
                UnitPriceShirts = CDbl(txtUnitPriceShirts.Text)
            Catch Exc As FormatException
                MsgBox("The value you entered for the price of " & _
                                "shirts is not valid" & _
                                vbCrLf & "Please try again")
                Exit Sub
            End Try
    
            ' Retrieve the number of this item
            ' Just in case the user types an invalid value,
            ' we are using a try...catch
            Try
                QuantityShirts = CInt(txtQuantityShirts.Text)
            Catch Exc As FormatException
                MsgBox("The value you entered for the number of " & _
                                "shirts is not valid" & _
                                vbCrLf & "Please try again")
                Exit Sub
            End Try
    
            Try
                UnitPricePants = CDbl(txtUnitPricePants.Text)
            Catch Exc As FormatException
                MsgBox("The value you entered for the price of " & _
                                "pants is not valid" & _
                                vbCrLf & "Please try again")
                Exit Sub
            End Try
    
            Try
                QuantityPants = CInt(txtQuantityPants.Text)
            Catch Exc As FormatException
                MsgBox("The value you entered for the number of " & _
                                "pants is not valid" & _
                                vbCrLf & "Please try again")
                Exit Sub
            End Try
    
            If (cbxNameItem1.Text = "None") Or _
               (cbxNameItem1.Text = "") Then
                QuantityItem1 = 0
                UnitPriceItem1 = 0.0
            Else
                Try
                    UnitPriceItem1 = CDbl(txtUnitPriceItem1.Text)
                Catch Exc As FormatException
                    MsgBox("The value you entered for the price is not valid" & _
                                    vbCrLf & "Please try again")
                    Exit Sub
                End Try
    
                Try
                    QuantityItem1 = CInt(txtQuantityItem1.Text)
                Catch Exc As FormatException
                    MsgBox("The value you entered is not valid" & _
                                    vbCrLf & "Please try again")
                    Exit Sub
                End Try
            End If
    
            If (cbxNameItem2.Text = "None") Or _
               (cbxNameItem2.Text = "") Then
                QuantityItem2 = 0
                UnitPriceItem2 = 0.0
            Else
                Try
                    UnitPriceItem2 = CDbl(txtUnitPriceItem2.Text)
                Catch Exc As FormatException
                    MsgBox("The value you entered for " & _
                        "the price is not valid" & _
                                    vbCrLf & "Please try again")
                    Exit Sub
                End Try
    
                Try
                    QuantityItem2 = CInt(txtQuantityItem2.Text)
                Catch Exc As FormatException
                    MsgBox("The value you entered is not valid" & _
                                    vbCrLf & "Please try again")
                    Exit Sub
                End Try
            End If
    
            If (cbxNameItem3.Text = "None") Or _
               (cbxNameItem3.Text = "") Then
                QuantityItem3 = 0
                UnitPriceItem3 = 0.0
            Else
                Try
                    UnitPriceItem3 = CDbl(txtUnitPriceItem3.Text)
                Catch Exc As FormatException
                    MsgBox("The value you entered for the " & _
                        "price is not valid" & _
                                    vbCrLf & "Please try again")
                    Exit Sub
                End Try
    
                Try
                    QuantityItem3 = CInt(txtQuantityItem3.Text)
                Catch Exc As FormatException
                    MsgBox("The value you entered is not valid" & _
                                    vbCrLf & "Please try again")
                    Exit Sub
                End Try
            End If
    
            If (cbxNameItem4.Text = "None") Or (cbxNameItem4.Text = "") Then
                QuantityItem4 = 0
                UnitPriceItem4 = 0.0
            Else
                Try
                    UnitPriceItem4 = CDbl(txtUnitPriceItem4.Text)
                Catch Exc As FormatException
                    MsgBox("The value you entered for the price is not valid" & _
                            vbCrLf & "Please try again")
                    Exit Sub
                End Try
    
                Try
                    QuantityItem4 = CInt(txtQuantityItem4.Text)
                Catch Exc As FormatException
                    MsgBox("The value you entered is not valid" & _
                            vbCrLf & "Please try again")
                    Exit Sub
                End Try
            End If
    
            ' Calculate the sub-total for this item
            SubTotalShirts = QuantityShirts * UnitPriceShirts
            SubTotalPants = QuantityPants * UnitPricePants
            SubTotalItem1 = QuantityItem1 * UnitPriceItem1
            SubTotalItem2 = QuantityItem2 * UnitPriceItem2
            SubTotalItem3 = QuantityItem3 * UnitPriceItem3
            SubTotalItem4 = QuantityItem4 * UnitPriceItem4
    
            ' Calculate the total based on sub-totals
            CleaningTotal = SubTotalShirts + SubTotalPants + _
                            SubTotalItem1 + SubTotalItem2 + _
                            SubTotalItem3 + SubTotalItem4
    
            TaxRate = CDbl(txtTaxRate.Text)
            ' Calculate the amount owed for the taxes
            TaxAmount = CleaningTotal * TaxRate / 100
            ' Add the tax amount to the total order
            NetPrice = CleaningTotal + TaxAmount
    
            ' Display the sub-total in the corresponding text box
            txtSubTotalShirts.Text = FormatNumber(SubTotalShirts)
            txtSubTotalPants.Text = FormatNumber(SubTotalPants)
            txtSubTotalItem1.Text = FormatNumber(SubTotalItem1)
            txtSubTotalItem2.Text = FormatNumber(SubTotalItem2)
            txtSubTotalItem3.Text = FormatNumber(SubTotalItem3)
            txtSubTotalItem4.Text = FormatNumber(SubTotalItem4)
    
            txtCleaningTotal.Text = FormatNumber(CleaningTotal)
            txtTaxAmount.Text = FormatNumber(TaxAmount)
            txtNetPrice.Text = FormatNumber(NetPrice)
    
            SaveCleaningOrder()
    End Sub
  5. In the Class Name combo box, select cbxOrderStatus
  6. In the Method Name combo box, select SelectedIndexChanged and implement the event as follows:
     
    Private Sub cbxOrderStatus_SelectedIndexChanged(ByVal sender As Object, _
                                                    ByVal e As System.EventArgs) _
                                       Handles cbxOrderStatus.SelectedIndexChanged
            SaveCleaningOrder()
    End Sub
  7. In the Class Name combo box, select dtpDatePickedUp
  8. In the Method Name combo box, select ValueChanged and implement the event as follows:
     
    Private Sub dtpDatePickedUp_ValueChanged(ByVal sender As Object, _
                                                 ByVal e As System.EventArgs) _
                                                 Handles dtpDatePickedUp.ValueChanged
            SaveCleaningOrder()
    End Sub
  9. In the Class Name combo box, select dtpTimePickedUp
  10. In the Method Name combo box, select ValueChanged and implement the event as follows:
     
    Private Sub dtpTimePickedUp_ValueChanged(ByVal sender As Object, _
                                                 ByVal e As System.EventArgs) _
                                                 Handles dtpTimePickedUp.ValueChanged
        SaveCleaningOrder()
    End Sub
  11. In the Class Name combo box, select btnClose
  12. 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
  13. Execute the application
  14. Create a cleaning order
  15. Click New Cleaning Order and create a few more cleaning orders
  16. Close the form and return to your programming environment

Locating an Element Using a Tag Name

To assist you with finding a node, the XmlDocument class is equipped with the GetElementByTagName() method which is overloaded with two versions. One of the syntaxes used is:

Public Overridable Function GetElementsByTagName ( _
	name As String _
) As XmlNodeList

This method takes as argument a string. The string must be the name of a node. If at least one node that holds that name exists in the file, this method returns a collection of the nodes with that name. If there is no node with that name, the collection is returned empty and there is no exception thrown.

Here is an example of calling the method:

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)

            ' Get a reference to the root node
            Dim RootElement As XmlElement = DOMDocument.DocumentElement

            ' Create a list of nodes whose name is Title
            Dim ListOfTitles As XmlNodeList = DOMDocument.GetElementsByTagName("title")
        End If
End Sub

Once you have a list of the nodes of a particular criterion, you can then act as you see fit. For example, you can look for a particular node that holds text of your choice. 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)

            ' Get a reference to the root node
            Dim RootElement As XmlElement = DOMDocument.DocumentElement

            ' Create a list of nodes whose name is Title
            Dim ListOfTitles As XmlNodeList = DOMDocument.GetElementsByTagName("title")

            For Each Node As XmlNode In ListOfTitles
                If Node.InnerText = "Her Alibi" Then

                End If
            Next
        End If
End Sub

Inserting an Element

 

Inserting an Element as a Last Child

Once again, consider our 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>
    <video>
	<title>The Day After Tomorrow</title>
	<director>Roland Emmerich</director>
	<length>124 Minutes</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>

Imagine you want to add a list of actors of the Her Alibi video. The first action to take is to locate the video, which you can do by calling the XmlDocument.GetElementsByTagName() method applied to a collection of nodes whose names are video. From this list of nodes, you can look for the node whose value is "Her Alibi". Once you have found this element, get a reference to its parent. Then add the new node as a child its parent. This can be done 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)

            ' Get a reference to the root node
            Dim RootElement As XmlElement = DOMDocument.DocumentElement

            ' Create a list of nodes whose name is Title
            Dim ListOfTitles As XmlNodeList = DOMDocument.GetElementsByTagName("title")

            ' Now you can check each node of the list
            For Each Node As XmlNode In ListOfTitles
                If Node.InnerText = "Her Alibi" Then

                    ' Create an element named Actors
                    Dim NewElement As XmlElement = DOMDocument.CreateElement("actors")
                    Dim Parent As XmlNode = Node.ParentNode
                    ' Add a new element named Actors to it
                    Parent.AppendChild(NewElement)
                    DOMDocument.Save(Filename)
                End If
            Next
        End If
End Sub

This would produce:

<?xml version="1.0" encoding="utf-8"?>
<videos>
  . . .
  <video>
    <title>Her Alibi</title>
    <director>Bruce Beresford</director>
    <length>94 Minutes</length>
    <format>DVD</format>
    <rating>PG-13</rating>
    <actors />
  </video>
  . . .
</videos>

This code creates an empty element. If you want to create an element that includes a value, create its text and add that text to the 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)

        ' Get a reference to the root node
        Dim RootElement As XmlElement = DOMDocument.DocumentElement

        ' Create a list of nodes whose name is Title
        Dim ListOfTitles As XmlNodeList = DOMDocument.GetElementsByTagName("title")

        ' Now you can check each node of the list
        For Each Node As XmlNode In ListOfTitles
            ' When you get to a node, look for the element's value
            ' If you find an element whose value is Her Alibi
            If Node.InnerText = "The Distinguished Gentleman" Then
                ' Create an element named Category
                Dim NewElement As XmlElement = DOMDocument.CreateElement("category")
                ' Create the text of the new element
                Dim TextCatetory As XmlText = DOMDocument.CreateTextNode("Comedy")
                ' Get a reference to the parent of the node we have found
                Dim Parent As XmlNode = Node.ParentNode
                ' Add the new element to the node we found
                Parent.AppendChild(NewElement)
                ' Specify the text of the new node
                Parent.LastChild.AppendChild(TextCatetory)
                ' Save the file
                DOMDocument.Save(Filename)
            End If
        Next
    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>
    <category>Comedy</category>
  </video>
  . . .
</videos>

Using the same approach combined with what we learned about adding an item, you can add a new element that itself has child nodes. 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)

        ' Get a reference to the root node
        Dim RootElement As XmlElement = DOMDocument.DocumentElement

        ' Create a list of nodes whose name is Title
        Dim ListOfTitles As XmlNodeList = DOMDocument.GetElementsByTagName("title")

        ' Now you can check each node of the list
        For Each Node As XmlNode In ListOfTitles
            ' When you get to a node, look for the element's value
            ' If you find an element whose value is The Day After Tomorrow
            If Node.InnerText = "The Day After Tomorrow" Then
                ' Create an element named Actors
                Dim NewElement As XmlElement = DOMDocument.CreateElement("actors")
                ' Get a reference to the parent of the node we have found
                Dim VideoElement As XmlNode = Node.ParentNode
                ' Add the new element to the node we found
                VideoElement.AppendChild(NewElement)

                ' Create an element as a child of the new element
                ' Specify its name as Actor
                NewElement = DOMDocument.CreateElement("actor")
                ' Create the text of the new element
                Dim TextActor As XmlText = DOMDocument.CreateTextNode("Dennis Quaid")
                ' Add the new Actor element to the Actors node
                VideoElement.LastChild.AppendChild(NewElement)
                ' Specify the text of the new node
                VideoElement.LastChild.LastChild.AppendChild(TextActor)

                ' In the same way, add the other Actor nodes
                NewElement = DOMDocument.CreateElement("actor")
                TextActor = DOMDocument.CreateTextNode("Jake Gyllenhaal")
                VideoElement.LastChild.AppendChild(NewElement)
                VideoElement.LastChild.LastChild.AppendChild(TextActor)

                NewElement = DOMDocument.CreateElement("actor")
                TextActor = DOMDocument.CreateTextNode("Emmy Rossum")
                VideoElement.LastChild.AppendChild(NewElement)
                VideoElement.LastChild.LastChild.AppendChild(TextActor)

                NewElement = DOMDocument.CreateElement("actor")
                TextActor = DOMDocument.CreateTextNode("Dash Mihok")
                VideoElement.LastChild.AppendChild(NewElement)
                VideoElement.LastChild.LastChild.AppendChild(TextActor)

                ' Save the file
                DOMDocument.Save(Filename)
            End If
        Next
    End If
End Sub

This would produce:

<?xml version="1.0" encoding="utf-8"?>
<videos>
  . . .
  <video>
    <title>The Day After Tomorrow</title>
    <director>Roland Emmerich</director>
    <length>124 Minutes</length>
    <format>DVD</format>
    <rating>PG-13</rating>
    <actors>
      <actor>Dennis Quaid</actor>
      <actor>Jake Gyllenhaal</actor>
      <actor>Emmy Rossum</actor>
      <actor>Dash Mihok</actor>
    </actors>
  </video>
</videos>

You can also insert one or more elements as children of an existing node after locating that node. Here is an example:

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>
    <category>Comedy</category>
  </video>
  <video>
    <title>Her Alibi</title>
    <director>Bruce Beresford</director>
    <length>94 Mins</length>
    <format>DVD</format>
    <rating>PG-13</rating>
    <actors />
  </video>
</videos>

Code Fragment:

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)

            ' Get a reference to the root node
            Dim RootElement As XmlElement = DOMDocument.DocumentElement

            ' Create a list of nodes whose name is Title
            Dim ListOfTitles As XmlNodeList = DOMDocument.GetElementsByTagName("title")

            ' Now you can check each node of the list
            For Each Node As XmlNode In ListOfTitles
                ' When you get to a node, look for the element's value
                ' If you find an element whose value is Her Alibi
                If Node.InnerText = "Her Alibi" Then
                    ' Get a reference to the video node that is 
                    ' the parent of the video titled Her Alibi
                    Dim VideoElement As XmlNode = Node.ParentNode

                    ' Create a list of the child nodes of the Her alibi video
                    Dim ListOfActors As XmlNodeList = VideoElement.ChildNodes

                    ' Visit each item of the collection
                    ' looking for an element named Actors
                    For Each ActorNode As XmlNode In ListOfActors
                        ' If you find an element named Actors
                        If ActorNode.Name = "actors" Then
                            ' Create a new element named Actor
                            ' Specify its name as Actor
                            Dim NewElement As XmlElement = DOMDocument.CreateElement("actor")
                            ' Create the text of the new element
                            Dim TextActor As XmlText = DOMDocument.CreateTextNode("Tom Selleck")
                            ' Add the new Actor element to the Actors node
                            VideoElement.LastChild.AppendChild(NewElement)
                            ' Specify the text of the new node
                            VideoElement.LastChild.LastChild.AppendChild(TextActor)

                            ' Add other Actor nodes
                            NewElement = DOMDocument.CreateElement("actor")
                            TextActor = DOMDocument.CreateTextNode("Paulina Porizkova")
                            VideoElement.LastChild.AppendChild(NewElement)
                            VideoElement.LastChild.LastChild.AppendChild(TextActor)

                            NewElement = DOMDocument.CreateElement("actor")
                            TextActor = DOMDocument.CreateTextNode("William Daniels")
                            VideoElement.LastChild.AppendChild(NewElement)
                            VideoElement.LastChild.LastChild.AppendChild(TextActor)

                            ' Save the file
                            DOMDocument.Save(Filename)

                            ' Stop, in this example, we don't expect another Actors node
                            Exit For
                        End If
                    Next
                End If
            Next
        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>
    <category>Comedy</category>
  </video>
  <video>
    <title>Her Alibi</title>
    <director>Bruce Beresford</director>
    <length>94 Minutes</length>
    <format>DVD</format>
    <rating>PG-13</rating>
    <actors>
      <actor>Tom Selleck</actor>
      <actor>Paulina Porizkova</actor>
      <actor>William Daniels</actor>
    </actors>
  </video>
</videos>

Inserting an Element Referencing a Sibling

Instead of simply adding a new node at the end of child nodes, you can specify any other position you want. For example, you may want the new node to precede an existing child node. To support this operation, the XmlNode class provides the InsertBefore() method. Its syntax is:

Public Overridable Function InsertBefore ( _
	newChild As XmlNode, _
	refChild As XmlNode _
) As XmlNode

The first argument of this method is the new node that will be added. The second argument is the sibling that will succeed the new node. Consider the following version of our 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>
        <category>Comedy</category>
    </video>
    <video>
	<title>Fatal Attraction</title>
	<director>Adrian Lyne</director>
	<length>119 Minutes</length>
	<format>DVD</format>
	<rating>R</rating>
    </video>
</videos>

Imagine you want to create a new category element below the director element whose name is Adrian Lyne. You can first get a list of videos. Inside of each video, check the nodes and find out whether the video has a director node whose text is Adrian Lyne. Once you find that node, you can add the new element after it.

As we have pointed out in previous sections and lessons, using a value such as the name of a director of a video to locate a node is not a smart idea because you could have various videos with the same director. In professional applications, always make sure you have a way to uniquely distinguish each node in a category or collection. For a video collection such as ours, you could create a node that has a shelf number or the ISBN number that is unique to each video, and use that number to identify a particular video.

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)

            ' Get a reference to the root node
            Dim RootElement As XmlElement = DOMDocument.DocumentElement

            ' Create a list of the videos
            Dim ListOfVideos As XmlNodeList = DOMDocument.GetElementsByTagName("video")

            ' visit each video
            For Each Node As XmlNode In ListOfVideos
                ' Within a video, create a list of its children
                Dim ListOfChildren As XmlNodeList = Node.ChildNodes

                ' Visit each child node
                For Each Director As XmlNode In ListOfChildren
                    ' If the child node is (a director and its name is) Adrian Lyne
                    If Director.InnerText = "Adrian Lyne" Then
                        ' Create an element named Category
                        Dim NewElement As XmlElement = DOMDocument.CreateElement("category")
                        ' Specify the text of the new element
                        NewElement.InnerText = "Drama"

                        ' Insert the new node below the Adrian Lyne node Director
                        Node.InsertAfter(NewElement, Director)

                        ' Save the file
                        DOMDocument.Save(Filename)

                        ' Stop
                        Exit For
                    End If
                Next
            Next
        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>
    <category>Comedy</category>
  </video>
  <video>
    <title>Fatal Attraction</title>
    <director>Adrian Lyne</director>
    <category>Drama</category>
    <length>119 Minutes</length>
    <format>DVD</format>
    <rating>R</rating>
  </video>
</videos>

In the same way, you can insert a new node after a child of a child (or of a child of a child of a child) of any node. If you want to new node to be positioned after an existing child node, you can call the XmlNode.InsertAfter() method. Its syntax is:

Public Overridable Function InsertAfter ( _
	newChild As XmlNode, _
	refChild As XmlNode _
) As XmlNode

Deleting Elements

 

Deleting an Element

If you have a node you do not want or do not need it anymore in the document, you can delete it. To delete a node, the XmlNode class provides the RemoveChild() method. Its syntax is:

Public Overridable Function RemoveChild(oldChild As XmlNode) As XmlNode

This method takes as argument the node to delete. If the node exists, it would be deleted and the method would return the node that was deleted. If the node does not exist, nothing would happen. To effectively use this method, you should first locate the particular node you want to delete. You can look for it using any of the logics we have applied so far. Once you find the node, you can then delete it. Consider the following document:

<?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>
    <category>Comedy</category>
  </video>
  <video>
    <title>Her Alibi</title>
    <director>Bruce Beresford</director>
    <length>94 Mins</length>
    <format>DVD</format>
    <rating>PG-13</rating>
    <actors />
  </video>
</videos>

Imagine you want to delete a node whose name is Director and whose value is Bruce Beresford. Here is an example of calling this method to perform the operation:

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)

        ' Get a reference to the root node
        Dim RootElement As XmlElement = DOMDocument.DocumentElement

        ' Create a list of the videos
        Dim ListOfVideos As XmlNodeList = DOMDocument.GetElementsByTagName("video")

        ' visit each video
        For Each Node As XmlNode In ListOfVideos
            ' Within a video, get a list of its children
            Dim ListOfChildren As XmlNodeList = Node.ChildNodes

            ' Visit each child node
            For Each Director As XmlNode In ListOfChildren
                ' If the child node is Bruce Beresford
                If Director.InnerText = "Bruce Beresford" Then
                    Node.RemoveChild(Director)

                    ' Save the file
                    DOMDocument.Save(Filename)

                    ' Stop
                    Exit For
                End If
            Next
        Next
    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>
    <category>Comedy</category>
  </video>
  <video>
    <title>Her Alibi</title>
    <length>94 Mins</length>
    <format>DVD</format>
    <rating>PG-13</rating>
    <actors />
  </video>
</videos>

Notice that the <director>Bruce Beresford</director> node is gone.

Clearing an Element of its Children

To delete all child nodes of a node, you can call the XmlNode.RemoveAll() method. Its syntax is:

Public Overridable Sub RemoveAll

When called, this method will remove all child nodes, if any, of their parent node. Consider the following XML file named videos.xml:

<?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>
    <video>
	<title>Other People's Money</title>
	<director>Alan Brunstein</director>
	<length>114 Minutes</length>
	<format>VHS</format>
	<rating>PG-13</rating>
    </video>
</videos>

Here is an example of calling the XmlNode.RemoveAll() method to delete all child nodes of any node named video in the document:

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)

            ' Get a reference to the root node
            Dim RootElement As XmlElement = DOMDocument.DocumentElement

            ' Create a list of the videos
            Dim ListOfVideos As XmlNodeList = DOMDocument.GetElementsByTagName("video")

            ' visit each video
            For Each Node As XmlNode In ListOfVideos
                ' Within a video, get a list of its children
                Dim ListOfChildren As XmlNodeList = Node.ChildNodes

                ' Visit each child node
                For Each Director As XmlNode In ListOfChildren
                    Node.RemoveAll()

                    ' Save the file
                    DOMDocument.Save(Filename)
                Next
            Next
        End If
End Sub

This would produce:

<?xml version="1.0" encoding="utf-8"?>
<videos>
  <video></video>
  <video></video>
  <video></video>
  <video></video>
</videos>

In the same way, you can first locate one particular parent node, and then delete all of its children by calling this method. Consider the following document:

<?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>The Day After Tomorrow</title>
	<director>Roland Emmerich</director>
	<length>124 Minutes</length>
	<format>DVD</format>
	<rating>PG-13</rating>
	<actors>
	    <actor>Dennis Quaid</actor>
	    <actor>Jake Gyllenhaal</actor>
	    <actor>Emmy Rossum</actor>
	    <actor>Dash Mihok</actor>
	</actors>
    </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>

Here is an example of deleting all child nodes of a video whose title is The Day After Tomorrow:

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)

        ' Get a reference to the root node
        Dim RootElement As XmlElement = DOMDocument.DocumentElement

        ' Create a list of the videos
        Dim ListOfVideos As XmlNodeList = DOMDocument.GetElementsByTagName("video")

        ' visit each video
        For Each Node As XmlNode In ListOfVideos
            ' Within a video, get a list of its children
            Dim ListOfChildren As XmlNodeList = Node.ChildNodes

            ' Visit each child node
            For Each TitleNode As XmlNode In ListOfChildren
                ' If the child node is Bruce Beresford
                If TitleNode.InnerText = "The Day After Tomorrow" Then
                    Node.RemoveAll()

                    ' Save the file
                    DOMDocument.Save(Filename)

                    ' Stop
                    Exit For
                End If
            Next
        Next
    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>
  </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>

 


Previous Copyright 2008, Yevol Next