Using XML in the .NET Framework • Chapter 8 |
375 |
Private Sub Page_Load(s As Object, e As EventArgs)
If Not Page.IsPostBack Then
Dim myDoc As New XmlDocument()
Dim myRdr As New XmlTextReader(Server.MapPath("Catalog2.xml")) myRdr.WhitespaceHandling = WhitespaceHandling.None myDoc.Load(myRdr)
Session("sessionDoc") = myDoc ' Put it in a session variable
Once the tree is loaded, we can load the list box with the InnerText property of the ProductName nodes.
For i = 0 To myDoc.DocumentElement.ChildNodes.Count - 1
lstProducts.Items.Add _
(myDoc.DocumentElement.ChildNodes(i).ChildNodes(1).InnerText)
Next i
myRdr.Close()
Next, let’s investigate how to retrieve the price of a selected product. On click of the Show Price button, we simply retrieve the tree from the session, and get to the Price node directly.The SelectedIndex property of the list box does a favor for us, as its Selected Index value will match the corresponding child’s ordinal position in the Catalog (DocumentElement). Figure 8.20 shows an excerpt of the relevant code that is used to retrieve the price of a selected product.The complete code is available in the XmlDom1.aspx file in the accompanying CD.
Figure 8.20 Partial Listing of XmlDom1.aspx
Private Sub showPrice(s As Object, e As EventArgs)
Dim i As Integer
Dim qty As Integer = 1
Dim price As Double
Dim myDoc As New XmlDocument()
myDoc = Session("sessionDoc")
i = lstProducts.SelectedIndex ' The Row number selected
qty = Integer.Parse(txtQty.Text)
price = Double.Parse _
(myDoc.DocumentElement.ChildNodes(i).ChildNodes(2).InnerText)
lblPrice.Text = FormatCurrency(price)
Continued