Accessing and Locating XML Elements |
|
Accessing the Nodes of a Collection
Accessing a Node by its Index in a Collection
The children of a node, that is, the members of a ChildNodes property, or the members of an XmlNodeList collection, can be accessed each by an index. The first node has an index of 0, the second has an index of 1, and so on.
To give you access to a node of the collection, the XmlNodeList class is equipped with an indexed property and a method named Item. Both produce the same result. For example, if a node has three children, to access the third child node, you can apply an index of 2 to its indexed property. Here is an example:
<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Chemistry</title>
</head>
<body>
<h3>Chemistry</h3>
<%
Dim xeElement As XmlElement
Dim xnlElements As XmlNodeList
Dim xdChemistry As New XmlDocument()
Dim strFileName = Server.MapPath("exercises/PeriodicTable.xml")
If File.Exists(strFilename) Then
Using fsVideo As New FileStream(strFileName, FileMode.Open, FileAccess.Read)
xdChemistry.Load(fsVideo)
xeElement = xdChemistry.DocumentElement
xnlElements = xeElement .ChildNodes
Response.Write("The third element is " & xnlElements(2).InnerText)
End Using
Else
Response.Write("The file " & strFilename & " was not found")
End If
%>
</body>
</html>
You can also use the Item() property to get the same result..
For Accessing Each Node
Using a For Each loop, you can access each node and perform the necessary action, such as displaying the values of its children. Here is an example:
<%@ Page Language="VB" %> <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Xml" %> <!DOCTYPE html> <html> <head runat="server"> <title>Chemistry</title> </head> <body> <h3>Chemistry</h3> <% Dim xeElement As XmlElement Dim xnlElements As XmlNodeList Dim xdChemistry As New XmlDocument() Dim strFileName = Server.MapPath("exercises/PeriodicTable.xml") If File.Exists(strFilename) Then Using fsVideo As New FileStream(strFileName, FileMode.Open, FileAccess.Read) xdChemistry.Load(fsVideo) xeElement = xdChemistry.DocumentElement xnlElements = xeElement.ChildNodes For Each node As XmlNode In xnlElements Response.Write("<br>" & node.InnerText) Next End Using Else Response.Write("The file " & strFilename & " was not found") End If %> </body> </html>
Accessing the Collection of Children of a Child Node
Every item of a ChildNodes collection is an XmlNode object. This means that every item of a ChildNodes collection possesses its own ChildNodes collection. This also means that the operations you would perform on a child node can be performed as well on a child node. This allows you to get the collection of nodes that a child node of another child has.Here is an example of accessing the child nodes of an element that itself is a child of another node:
PeriodicTable.xml
<?xml version="1.0" encoding="utf-8"?> <chemistry> <element> <atomic-number>1</atomic-number> <element-name>Hydrogen</element-name> <symbol>H</symbol> <atomic-mass>1.0079</atomic-mass> </element> <element> <atomic-number>2</atomic-number> <element-name>Helium</element-name> <symbol>He</symbol> <atomic-mass>4.002682</atomic-mass> </element> <element> <atomic-number>3</atomic-number> <element-name>Lithium</element-name> <symbol>Li</symbol> <atomic-mass>6.941</atomic-mass> </element> <element> <atomic-number>4</atomic-number> <element-name>Berylium</element-name> <symbol>Be</symbol> <atomic-mass>9.0122</atomic-mass> </element> <element> <atomic-number>5</atomic-number> <element-name>Boron</element-name> <symbol>B</symbol> <atomic-mass>10.811</atomic-mass> </element> <element> <atomic-number>6</atomic-number> <element-name>Carbon</element-name> <symbol>C</symbol> <atomic-mass>12.011</atomic-mass> </element> <element> <atomic-number>7</atomic-number> <element-name>Nitrogen</element-name> <symbol>N</symbol> <atomic-mass>14.0067</atomic-mass> </element> <element> <atomic-number>8</atomic-number> <element-name>Oxygen</element-name> <symbol>O</symbol> <atomic-mass>15.9994</atomic-mass> </element> <element> <atomic-number>9</atomic-number> <element-name>Fluorine</element-name> <symbol>F</symbol> <atomic-mass>18.9984</atomic-mass> </element> <element> <atomic-number>10</atomic-number> <element-name>Neon</element-name> <symbol>Ne</symbol> <atomic-mass>20.1797</atomic-mass> </element> </chemistry>
chemistry.aspx
<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Periodic Table</title>
</head>
<body>
<h3>Chemistry - Periodic Table</h3>
<%
Dim i As Integer
Dim xnElement As XmlNode
Dim xeElement As XmlElement
Dim xnlElements As XmlNodeList
Dim xnlProperties As XmlNodeList
Dim xdPeriodicTable As New XmlDocument()
Dim strElementsFile = Server.MapPath("exercises/PeriodicTable.xml")
If File.Exists(strElementsFile) Then
Using fsPeriodicTable As New FileStream(strElementsFile, FileMode.Open, FileAccess.Read)
xdPeriodicTable.Load(fsPeriodicTable)
xeElement = xdPeriodicTable.DocumentElement
xnlElements = xeElement.ChildNodes
Response.Write("<table border=5><tr><td><b>Atomic #<b></td><td><b>Symbol</b></td>")
Response.Write("<td><b>Element</b></td><td><b>Mass</b></td></tr>")
For i = 0 To xnlElements.Count - 1
xnElement = xnlElements(i)
xnlProperties = xnElement.ChildNodes
Response.Write("<tr><td>" & xnlProperties(0).InnerText)
Response.Write("</td><td>" & xnlProperties(1).InnerText)
Response.Write("</td><td>" & xnlProperties(2).InnerText)
Response.Write("</td><td>" & xnlProperties(3).InnerText & "</td></tr>")
Next
Response.Write("</table>")
End Using
Else
Response.Write("The file " & strElementsFile & " was not found")
End If
%>
</body>
</html>
This would produce:
Instead of using the indexed property, the XmlNodeList class implements the IEnumerable interface. This allows you to use a For Each loop to visit each node of the collection.
To better manage and manipulate the nodes of a collection of nodes, you must be able to access the desired node. The XmlNode class combined with the XmlNodeList class provide various means of getting to a node and taking the appropriate actions.
The Parent of a Node
Not all nodes have children, obviously. For example, the title node of our videos.xml file does not have children. To find out whether a node has children, check its HasChildNodes Boolean property that is declared as follows:
Public Overridable ReadOnly Property HasChildNodes As Boolean
If a node is a child, to get its parent, you can access its ParentNode property:
Public Overridable ReadOnly Property ParentNode As XmlNode
The First Child Node
The children of a nesting node are also recognized by their sequence. For our videos.xml file, the first line is called the first child of the DOM. This would be:
<?xml version="1.0" encoding="utf-8"?>
After identifying or locating a node, the first node that immediately follows it is referred to as its first child. In our videos.xml file, the first child of the first video node is the <title>The Distinguished Gentleman</title> element. The first child of the second <video> node is <title>Her Alibi</title>.
In the .NET Framework, the first child of a node can be retrieved by accessing the XmlNode.FirstChild property declared as follows:
Public Overridable ReadOnly Property FirstChild As XmlNode
To get the first child of a node, you can access the FirstChild property of the DocumentElement object of the DOM. Once you get that node, you can then do what you judge necessary. Here is an example:
states.xml
<?xml version="1.0" encoding="utf-8"?> <states> <state> <name>Alabama</name> <abbreviation>AL</abbreviation> <area-sqr-km>135775</area-sqr-km> <area-sqr-miles>52423</area-sqr-miles> <admission-union-year>1819</admission-union-year> <admission-union-order>22</admission-union-order> <capital>Montgomery</capital> </state> <state> <name>Alaska</name> <abbreviation>AK</abbreviation> <area-sqr-km>1700139</area-sqr-km> <area-sqr-miles>656424</area-sqr-miles> <admission-union-year>1959</admission-union-year> <admission-union-order>49</admission-union-order> <capital>Juneau</capital> </state> <state> <name>Arizona</name> <abbreviation>AZ</abbreviation> <area-sqr-km>295276</area-sqr-km> <area-sqr-miles>114006</area-sqr-miles> <admission-union-year>1912</admission-union-year> <admission-union-order>48</admission-union-order> <capital>Phoenix</capital> </state> <state> <name>Arkansas</name> <abbreviation>AR</abbreviation> <area-sqr-km>137742</area-sqr-km> <area-sqr-miles>53182</area-sqr-miles> <admission-union-year>1836</admission-union-year> <admission-union-order>25</admission-union-order> <capital>Little Rock</capital> </state> <state> <name>California</name> <abbreviation>CA</abbreviation> <area-sqr-km>424002</area-sqr-km> <area-sqr-miles>163707</area-sqr-miles> <admission-union-year>1850</admission-union-year> <admission-union-order>31</admission-union-order> <capital>Sacramento</capital> </state> <state> <name>Colorado</name> <abbreviation>CO</abbreviation> <area-sqr-km>269620</area-sqr-km> <area-sqr-miles>104100</area-sqr-miles> <admission-union-year>1876</admission-union-year> <admission-union-order>38</admission-union-order> <capital>Denver</capital> </state> </states>
Exercise.aspx
<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>
<!DOCTYPE html>
<html>
<head runat="server">
<script runat="server">
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim lstStates As XmlNodeList
Dim strFileName = Server.MapPath("exercises/states.xml")
Dim xdStates As New XmlDocument()
If File.Exists(strFileName) Then
Using fsStates As New FileStream(strFileName, FileMode.Open, FileAccess.Read)
xdStates.Load(fsStates)
lstStates = xdStates.DocumentElement.ChildNodes
For Each node As XmlNode In lstStates
lbxStates.Items.Add(node.FirstChild.innerText)
Next
End Using
Else
Response.Write("The file " + strFileName + " was not found.")
End If
End Sub
</script>
<title>States</title>
</head>
<body>
<h3>States</h3>
<form id="frmStates" runat="server">
<asp:ListBox id="lbxStates" Height="110px" runat="server"></asp:ListBox>
</form>
</body>
</html>
This would produce:
The Last Child Node
As opposed to the first child, the child node that immediately precedes the end-tag of the parent node is called the last child. To get the last child of a node, you can access its XmlNode.LastChild property that is declared as follows:
Public Overridable ReadOnly Property LastChild As XmlNode
Here is an example:
<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>
<!DOCTYPE html>
<html>
<head runat="server">
<script runat="server">
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim lstStates As XmlNodeList
Dim strFileName = Server.MapPath("exercises/states.xml")
Dim xdStates As New XmlDocument()
If File.Exists(strFileName) Then
Using fsStates As New FileStream(strFileName, FileMode.Open, FileAccess.Read)
xdStates.Load(fsStates)
lstStates = xdStates.DocumentElement.ChildNodes
For Each node As XmlNode In lstStates
lbxStates.Items.Add(node.LastChild.innerText)
Next
End Using
Else
Response.Write("The file " + strFileName + " was not found.")
End If
End Sub
</script>
<title>States</title>
</head>
<body>
<h3>Capitals</h3>
<form id="frmStates" runat="server">
<asp:ListBox id="lbxStates" Height="110px" runat="server"></asp:ListBox>
</form>
</body>
</html>
This would produce:
The Siblings of a Node
The child nodes that are nested in a parent node and share the same level are referred to as siblings. To access the sibling of a node, you can use its XmlNode.NextSibling property, which is declared as follows:
Public Overridable ReadOnly Property NextSibling As XmlNode
Once you have a node, such as getting it from the first or the last child, you can directly get its next sibling as we saw previously. In fact, from the next sibling of a first or last node, you can keep calling the next sibling until you reach the desired sibling, that is, until you reach the actual node you want to access. Here are examples:
<%@ Page Language="VB" %> <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Xml" %> <!DOCTYPE html> <html> <head runat="server"> <title>States</title> </head> <body> <h3>States</h3> <% Dim lstStates As XmlNodeList Dim strFileName = Server.MapPath("exercises/states.xml") Dim xdStates As New XmlDocument() If File.Exists(strFileName) Then Using fsStates As New FileStream(strFileName, FileMode.Open, FileAccess.Read) xdStates.Load(fsStates) lstStates = xdStates.DocumentElement.ChildNodes Response.Write("<table border=4><tr><td><b>Name</b></td><td><b>Abbreviation</b></td><td><b>Area(Sqr Km)</b></td><td><b>Area(Sqr Mi)</b></td><td><b>Year of Admission to Union</b></td><td><b>Order of Admission to Union</b></td><td><b>Capital</b></td></tr>") For Each node As XmlNode In lstStates Response.Write("<tr><td>" & node.FirstChild.InnerText & "</td><td style='text-align: center'>" & node.FirstChild.NextSibling.InnerText & "</td><td style='text-align: right'>" & node.FirstChild.NextSibling.NextSibling.InnerText & "</td><td style='text-align: right'>" & node.FirstChild.NextSibling.NextSibling.NextSibling.InnerText & "</td><td style='text-align: center'>" & node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.InnerText & "</td><td style='text-align: center'>" & node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText & "</td><td>" & node.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText & "</td></tr>") Next Response.Write("</table>") End Using Else Response.Write("The file " & strFileName & " was not found.") End If %> </body> </html>
This would produce:
Accessing an Element by its Tag Name
To assist you with finding a node, the XmlDocument class is equipped with a method named GetElementByTagName. It is overloaded with two versions. One of the versions uses the following syntax:
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:
Fun Department Store: StoreItems.xml
<?xml version="1.0" encoding="utf-8"?> <StoreItems> <StoreItem> <ItemNumber>177314</ItemNumber> <Manufacturer>Ralph Lauren</Manufacturer> <Category>Girls</Category> <SubCategory>Shirts</SubCategory> <ItemName>Girls 2-6X Short-Sleeved Mesh Polo Shirt</ItemName> <ItemSize>3T</ItemSize> <UnitPrice>34.95</UnitPrice> </StoreItem> <StoreItem> <ItemNumber>771535</ItemNumber> <Manufacturer>Collentra Studio</Manufacturer> <Category>Women</Category> <SubCategory>Hats</SubCategory> <ItemName>Straw Wraparound Hat - Black</ItemName> <ItemSize>S</ItemSize> <UnitPrice>15</UnitPrice> </StoreItem> <StoreItem> <ItemNumber>239530</ItemNumber> <Manufacturer>Kenneth Cole</Manufacturer> <Category>Women</Category> <SubCategory>Dresses</SubCategory> <ItemName>Three-Quarter Sleeved Dress</ItemName> <ItemSize>M</ItemSize> <UnitPrice>164.5</UnitPrice> </StoreItem> <StoreItem> <ItemNumber>386174</ItemNumber> <Manufacturer>AK Anne Klein</Manufacturer> <Category>Baby Girls</Category> <SubCategory>Dresses</SubCategory> <ItemName>Baby Girls 12-24 Months Floral Bow Dress</ItemName> <ItemSize>18M</ItemSize> <UnitPrice>9.95</UnitPrice> </StoreItem> <StoreItem> <ItemNumber>221573</ItemNumber> <Manufacturer>Nautica</Manufacturer> <Category>Baby Girls</Category> <SubCategory> </SubCategory> <ItemName>Baby Girls 12-24 Months Lace Two-Piece Set</ItemName> <ItemSize>12M</ItemSize> <UnitPrice>40</UnitPrice> </StoreItem> <StoreItem> <ItemNumber>959535</ItemNumber> <Manufacturer>Ralph Lauren</Manufacturer> <Category>Baby Boys</Category> <SubCategory>Jackets</SubCategory> <ItemName>Baby Boys 12-24 Months Richmond Bomber Jacket</ItemName> <ItemSize>9M</ItemSize> <UnitPrice>64</UnitPrice> </StoreItem> <StoreItem> <ItemNumber>280076</ItemNumber> <Manufacturer>Juaro Collections</Manufacturer> <Category>Women</Category> <SubCategory>Hats</SubCategory> <ItemName>Newport Bow Hat</ItemName> <ItemSize></ItemSize> <UnitPrice>25</UnitPrice> </StoreItem> <StoreItem> <ItemNumber>152896</ItemNumber> <Manufacturer>Polo Ralph Lauren</Manufacturer> <Category>Men</Category> <SubCategory>Shirts</SubCategory> <ItemName>Classic-Fit Short-Sleeved Cotton Interlock Polo Shirt</ItemName> <ItemSize>S</ItemSize> <UnitPrice>75</UnitPrice> </StoreItem> <StoreItem> <ItemNumber>292915</ItemNumber> <Manufacturer>Kenneth Cole</Manufacturer> <Category>Women</Category> <SubCategory>Dresses</SubCategory> <ItemName>Three-Quarter Sleeved Dress</ItemName> <ItemSize>L</ItemSize> <UnitPrice>145.5</UnitPrice> </StoreItem> <StoreItem> <ItemNumber>406615</ItemNumber> <Manufacturer>AK Anne Klein</Manufacturer> <Category>Baby Girls</Category> <SubCategory>Dresses</SubCategory> <ItemName>Baby Girls 12-24 Months Floral Bow Dress</ItemName> <ItemSize>12M</ItemSize> <UnitPrice>9.95</UnitPrice> </StoreItem> </StoreItems>
Fun Department Store: StoreItems.aspx
<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Fun Department Store - Store Items</title>
</head>
<body>
<h3>Fun Department Store - Store Items</h3>
<%
Dim i = 1
Dim xnStoreItem As XmlNode
Dim xnlStoreItems As XmlNodeList
Dim xdStoreItems As New XmlDocument()
Dim strStoreItemsFile As String = Server.MapPath("StoreItems1.xml")
If File.Exists(strStoreItemsFile) Then
xdStoreItems.Load(strStoreItemsFile)
xnlStoreItems = xdStoreItems.GetElementsByTagName("ItemNumber")
Response.Write("<table border=5><tr><td>#</td><td><b>Item Nbr</b></td><td><b>Manufacturer</b></td><td><b>Category</b></td><td><b>Sub-Category</b></td><td><b>Item Name</b></td><td><b>Size</b></td><td><b>Unit Price</b></td></tr>")
For Each xnStoreItem In xnlStoreItems
Response.Write("<tr><td>" & CStr(i) & "</td>")
Response.Write("<td>" & xnStoreItem.InnerText & "</td>")
Response.Write("<td>" & xnStoreItem.NextSibling.InnerText & "</td>")
Response.Write("<td>" & xnStoreItem.NextSibling.NextSibling.InnerText & "</td>")
Response.Write("<td>" & xnStoreItem.NextSibling.NextSibling.NextSibling.InnerText & "</td>")
Response.Write("<td>" & xnStoreItem.NextSibling.NextSibling.NextSibling.NextSibling.InnerText & "</td>")
Response.Write("<td>" & xnStoreItem.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText & "</td>")
Response.Write("<td>" & CDbl(xnStoreItem.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText) & "</td></tr>")
i = i + 1
Next
Response.Write("</table>")
End If
%>
</body>
</html>
Locating an Element
Introduction
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 to the root, you can get a collection of its children. After getting a collection of the children 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 get a collection of the child nodes of that node and proceed. 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 file, you should make sure that you can uniquely identify each element.
Fortunately, the System.Xml namespace provides various means of looking for a node in an XML file.
Locating an Element as an XML Node
You can locate an element using a reference to its XML node. That is, by using the characteristics of parent, child (first or last), or sibling (next sibling, etc), you can reach a node and compare it either to a reference to an existing node or to a characteristic of the node, such as its value (text, or inner text). Here is an example:
Lambda SquareApartments: apartments.xml
<?xml version="1.0" encoding="UTF-8"?> <apartments> <apartment> <unit-code>139749</unit-code> <apartment-number>109</apartment-number> <bedrooms>2</bedrooms> <bathrooms>2</bathrooms> <monthly-rate>1150</monthly-rate> <security-deposit>650</security-deposit> <occupancy-status>Available</occupancy-status> </apartment> <apartment> <unit-code>844850</unit-code> <apartment-number>305</apartment-number> <bedrooms>2</bedrooms> <bathrooms>1</bathrooms> <monthly-rate>1100</monthly-rate> <security-deposit>600</security-deposit> <occupancy-status>Needs Repair</occupancy-status> </apartment> <apartment> <unit-code>138408</unit-code> <apartment-number>307</apartment-number> <bedrooms>3</bedrooms> <bathrooms>2</bathrooms> <monthly-rate>1350</monthly-rate> <security-deposit>850</security-deposit> <occupancy-status>Available</occupancy-status> </apartment> <apartment> <unit-code>308505</unit-code> <apartment-number>312</apartment-number> <bedrooms>2</bedrooms> <bathrooms>1</bathrooms> <monthly-rate>1075</monthly-rate> <security-deposit>600</security-deposit> <occupancy-status>Available</occupancy-status> </apartment> </apartments>
Lambda Square Apartments: newapartment.aspx
<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>
<!DOCTYPE html>
<html>
<head runat="server">
<script runat="server">
Sub btnCreateClick(ByVal sender As Object, ByVal e As EventArgs)
Dim found As Boolean
Dim unitCode As String
Dim xnApartment As XmlNode
Dim xeApartment As XmlElement
Dim xnlApartments As XmlNodeList
Dim xdApartments As New XmlDocument()
Dim strFileName = Server.MapPath("apartments.xml")
found = False
If File.Exists(strFileName) Then
Using fsApartments As New FileStream(strFileName, FileMode.Open, FileAccess.Read)
xdApartments.Load(fsApartments)
' Get a reference to the root
xeApartment = xdApartments.DocumentElement
' Get a list of the child nodes of the root
xnlApartments = xeApartment.ChildNodes
unitCode = txtUnitCode.Text
For Each xnApartment In xnlApartments
If xnApartment.FirstChild.InnerText = unitCode Then
found = True
Exit For
End If
Next
End Using
If found = True Then
lblMessage.Text = "An apartment with that unit code exists already."
Else
' Reset the form
txtUnitCode.Text = ""
lblMessage.Text = ""
txtBedrooms.Text = ""
txtBathrooms.Text = ""
txtMonthlyRate.Text = ""
txtSecurityDeposit.Text = ""
ddlOccupanciesStatus.SelectedItem.Text = "Other"
End If
End If
End Sub
</script>
<style>
#container
{
margin: auto;
width: 450px;
}
</style>
<title>Lambda Square Apartments - New Apartment</title>
</head>
<body>
<form id="frmNewApartment" runat="server">
<div id="container">
<h3>Lambda Square Apartments - New Apartment</h3>
<table>
<tr>
<td><b>Unit Code:</b></td>
<td><asp:TextBox id="txtUnitCode" style="width: 65px" runat="server"></asp:TextBox></td>
<td><b>Apartment #:</b></td>
<td><asp:TextBox id="txtApartmentNumber" style="width: 65px" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><b>Bedrooms:</b></td>
<td><asp:TextBox id="txtBedrooms" style="width: 65px;" runat="server"></asp:TextBox></td>
<td><b>Bathrooms:</b></td>
<td><asp:TextBox id="txtBathrooms" style="width: 65px;" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><b>Monthly Rate:</b></td>
<td><asp:TextBox id="txtMonthlyRate" style="width: 65px;" runat="server"></asp:TextBox></td>
<td><b>Security Deposit:</b></td>
<td><asp:TextBox id="txtSecurityDeposit" style="width: 65px" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><b>Occupancy Status:</b></td>
<td><asp:DropDownList id="ddlOccupanciesStatus" Width="100px" runat="server">
<asp:ListItem>Other</asp:ListItem>
<asp:ListItem>Available</asp:ListItem>
<asp:ListItem>Occupied</asp:ListItem>
<asp:ListItem>Not Ready</asp:ListItem>
<asp:ListItem>Needs Repair</asp:ListItem>
<asp:ListItem>Needs Renovation</asp:ListItem>
</asp:DropDownList></td>
<td> </td>
<td><asp:Button id="btnCreate" Text="Create" Width="75px"
OnClick="btnCreateClick" runat="server"></asp:Button></td>
</tr>
</table>
<asp:Label id="lblMessage" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
Here is an example of using the webpage:
Locating an Element Using its Index Inside the List of Nodes
We know that the XmlNodeList class is equipped with an indexed propery. You can use this characteristic to locate a node. Here is an example:
Watts A Loan: employees.xml
<?xml version="1.0" encoding="utf-8"?> <Employees> <Employee> <EmployeeNumber>293-747</EmployeeNumber> <FirstName>Catherine</FirstName> <LastName>Watts</LastName> <Title>Owner</Title> </Employee> <Employee> <EmployeeNumber>492-947</EmployeeNumber> <FirstName>Sandrine</FirstName> <LastName>Amiens</LastName> <Title>Assistant Manager</Title> </Employee> <Employee> <EmployeeNumber>240-750</EmployeeNumber> <FirstName>Jeannette</FirstName> <LastName>Gustman</LastName> <Title>Accounts Representative</Title> </Employee> <Employee> <EmployeeNumber>804-685</EmployeeNumber> <FirstName>Melissa</FirstName> <LastName>Browns</LastName> <Title>Customer Accounts Representative</Title> </Employee> <Employee> <EmployeeNumber>429-374</EmployeeNumber> <FirstName>Jake</FirstName> <LastName>Leighton</LastName> <Title>Accounts Manager</Title> </Employee> <Employee> <EmployeeNumber>836-486</EmployeeNumber> <FirstName>Ernest</FirstName> <LastName>Thomas</LastName> <Title>Accounts Representative</Title> </Employee> </Employees>
Watts A Loan: employees.aspx
<%@ Page Language="VB" %> <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Xml" %> <!DOCTYPE html> <html> <head runat="server"> <title>Watts A Loan - Employees</title> </head> <body> <h3>Watts A Loan - Employees</h3> <% Dim i As Integer Dim xnEmployee As XmlNode Dim xdEmployees As New XmlDocument() Dim xnlEmployees, xnlRecords As XmlNodeList Dim strEmployeesFile = Server.MapPath("employees.xml") If File.Exists(strEmployeesFile) Then Using fsEmployees As New FileStream(strEmployeesFile, FileMode.Open, FileAccess.Read) xdEmployees.Load(fsEmployees) xnlEmployees = xdEmployees.DocumentElement.ChildNodes Response.Write("<table border=6><tr><td><b>Employee #</b></td><td><b>First Name</b></td><td><b>Last Name</b></td><td><b>Title</b></td></tr>") For i = 0 To xnlEmployees.Count - 1 xnEmployee = xnlEmployees(i) xnlRecords = xnEmployee.ChildNodes Response.Write("<tr>") Response.Write("<td style='text-align: center'>" & xnlRecords(0).InnerText & "</td>") Response.Write("<td>" & xnlRecords(1).InnerText & "</td>") Response.Write("<td>" & xnlRecords(2).InnerText & "</td>") Response.Write("<td>" & xnlRecords(3).InnerText & "</td></tr>") Next Response.Write("</table>") End Using Else Response.Write("The file " & strEmployeesFile & " was not found.") End If %> </body> </html>
This would produce:
In the same way, you can go through the indexes of the children of a node to locate a node by comparing its value (text) to a known value. Here is an example:
Lambda Square Apartments: allocations.xml
<?xml version="1.0" encoding="UTF-8"?> <Allocations> <Allocation> <LoanNumber>100001</LoanNumber> <EmployeeNumber>429-374</EmployeeNumber> <DateLoanApplied>2014-05-08</DateLoanApplied> <FirstName>Joanne</FirstName> <LastName>Sinton</LastName> <LoanType>Personal Loan</LoanType> <DateLoanApproved>2014-06-16</DateLoanApproved> <LoanAmount>6500</LoanAmount> <InterestRate>12.65</InterestRate> <Periods>36</Periods> <InterestAmount>2466.75</InterestAmount> <FutureValue>8966.75</FutureValue> <MonthlyPayment>249.08</MonthlyPayment> <PaymentStartDate>2014-07-30</PaymentStartDate> </Allocation> <Allocation> <LoanNumber>100002</LoanNumber> <EmployeeNumber>492-947</EmployeeNumber> <DateLoanApplied>2014-08-22</DateLoanApplied> <FirstName>Helene</FirstName> <LastName>Fuchs</LastName> <LoanType>Boat Purchase</LoanType> <DateLoanApproved>2014-08-22</DateLoanApproved> <LoanAmount>16500</LoanAmount> <InterestRate>10.20</InterestRate> <Periods>60</Periods> <InterestAmount>8415</InterestAmount> <FutureValue>24915</FutureValue> <MonthlyPayment>415.25</MonthlyPayment> <PaymentStartDate>2014-09-30</PaymentStartDate> </Allocation> <Allocation> <LoanNumber>100003</LoanNumber> <EmployeeNumber>429-374</EmployeeNumber> <DateLoanApplied>2014-08-22</DateLoanApplied> <FirstName>Alexander</FirstName> <LastName>Lozanski</LastName> <LoanType>Furniture</LoanType> <DateLoanApproved>2014-08-28</DateLoanApproved> <LoanAmount>2258.75</LoanAmount> <InterestRate>14.25</InterestRate> <Periods>30</Periods> <InterestAmount>804.68</InterestAmount> <FutureValue>3063.43</FutureValue> <MonthlyPayment>102.12</MonthlyPayment> <PaymentStartDate>2014-09-30</PaymentStartDate> </Allocation> <Allocation> <LoanNumber>100004</LoanNumber> <EmployeeNumber>836-486</EmployeeNumber> <DateLoanApplied>2014-08-24</DateLoanApplied> <FirstName>Gerard</FirstName> <LastName>Valleys</LastName> <LoanType>Car Financing</LoanType> <DateLoanApproved>2014-10-05</DateLoanApproved> <LoanAmount>22748</LoanAmount> <InterestRate>10.25</InterestRate> <Periods>60</Periods> <InterestAmount>11658.35</InterestAmount> <FutureValue>34406.35</FutureValue> <MonthlyPayment>573.44</MonthlyPayment> <PaymentStartDate>2014-11-30</PaymentStartDate> </Allocation> </Allocations>
Lambda Square Apartments: allocations.aspx
<%@ Page Language="VB" %> <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Xml" %> <!DOCTYPE html> <html> <head runat="server"> <title>Watts A Loan - Loans Allocations</title> </head> <body> <h3>Watts A Loan - Loans Allocations</h3> <% Dim strEmployee As String Dim lviAllocation As ListViewItem Dim xnAllocation, xnEmployee As XmlNode Dim xdAllocations, xdEmployees As New XmlDocument() Dim strEmployeesFile = Server.MapPath("employees.xml") Dim strAllocationsFile = Server.MapPath("allocations.xml") Dim xnlEmployees, xnlAllocations, xnlRecords As XmlNodeList If File.Exists(strAllocationsFile) Then Using fsAllocations As New FileStream(strAllocationsFile, FileMode.Open, FileAccess.Read) xdAllocations.Load(fsAllocations) xnlAllocations = xdAllocations.DocumentElement.ChildNodes Response.Write("<table border=1><tr><td><b>Loan #</b></td>") Response.Write("<td><b>Employee</b></td><td><b>Date Loan Applied</b></td>") Response.Write("<td><b>First Name</b></td><td><b>Last Name</b></td>") Response.Write("<td><b>Loan Type</b></td><td><b>Date Loan Approved</b></td>") Response.Write("<td><b>Loan Amount</b></td><td><b>Interest Rate</b></td>") Response.Write("<td><b>Periods</b></td><td><b>Interest Amount</b></td>") Response.Write("<td><b>Future Value</b></td><td><b>Monthly Payment</b></td>") Response.Write("<td><b>Payment Start Date</b></td></tr>") For i As Integer = 0 To xnlAllocations.Count - 1 xnAllocation = xnlAllocations(i) Response.Write("<tr><td>" & xnAllocation.ChildNodes(0).InnerText & "</td>") ' Loan Number strEmployee = xnAllocation.ChildNodes(1).InnerText If File.Exists(strEmployeesFile) Then Using fsEmployees As New FileStream(strEmployeesFile, FileMode.Open, FileAccess.Read) xdEmployees.Load(fsEmployees) xnlEmployees = xdEmployees.DocumentElement.ChildNodes For j As Integer = 0 To xnlEmployees.Count - 1 xnEmployee = xnlEmployees(j) xnlRecords = xnEmployee.ChildNodes If xnlRecords(0).InnerText = xnAllocation.ChildNodes(1).InnerText Then strEmployee &= ": " & xnlRecords(1).InnerText & " " & xnlRecords(2).InnerText Exit For End If Next End Using End If Response.Write("<td>" & strEmployee & "</td>") ' Employee Number and Name Response.Write("<td>" & xnAllocation.ChildNodes(2).InnerText & "</td>") ' Date Loan Applied Response.Write("<td>" & xnAllocation.ChildNodes(3).InnerText & "</td>") ' Customer First Name Response.Write("<td>" & xnAllocation.ChildNodes(4).InnerText & "</td>") ' Customer Last Name Response.Write("<td>" & xnAllocation.ChildNodes(5).InnerText & "</td>") ' Loan Type Response.Write("<td>" & xnAllocation.ChildNodes(6).InnerText & "</td>") ' Date Loan Approved Response.Write("<td>" & FormatNumber(xnAllocation.ChildNodes(7).InnerText) & "</td>") ' Loan Amount Response.Write("<td>" & xnAllocation.ChildNodes(8).InnerText & "%</td>") ' Interest Rate Response.Write("<td>" & xnAllocation.ChildNodes(9).InnerText & " months</td>") ' Periods Response.Write("<td>" & FormatNumber(xnAllocation.ChildNodes(10).InnerText) & "</td>") ' Interest Amount Response.Write("<td>" & FormatNumber(xnAllocation.ChildNodes(11).InnerText) & "</td>") ' Future Value Response.Write("<td>" & xnAllocation.ChildNodes(12).InnerText & "</td>") ' Monthly Payment Response.Write("<td>" & xnAllocation.ChildNodes(13).InnerText & "</td></tr>") ' Payment Start Date Next Response.Write("</table>") End Using End If %> </body> </html>
This would produce:
Locating an Element Using its Index on the XML Node
While the XmlNodeList class has an indexed property, remember that every one of its items is of type XmlNode. In turn, the XmlNode class has its own indexed property. In the above code, we first declared a variable to hold the list from that indexed property: xnEmployee = xnlEmployees(i)
You don't have to first declare a a variable to hold the list of child nodes. You can access the indexes directly. Here is an example:
Lambda Square Apartments: payments.xml
<?xml version="1.0" encoding="UTF-8"?> <Payments> <Payment> <ReceiptNumber>100001</ReceiptNumber> <PaymentDate>2014-07-25</PaymentDate> <EmployeeNumber>240-750</EmployeeNumber> <LoanNumber>100001</LoanNumber> <PaymentAmount>249.08</PaymentAmount> <Balance>8717.67</Balance> </Payment> <Payment> <ReceiptNumber>100002</ReceiptNumber> <PaymentDate>2014-08-28</PaymentDate> <EmployeeNumber>804-685</EmployeeNumber> <LoanNumber>100001</LoanNumber> <PaymentAmount>249.08</PaymentAmount> <Balance>8468.59</Balance> </Payment> <Payment> <ReceiptNumber>100003</ReceiptNumber> <PaymentDate>2014-09-24</PaymentDate> <EmployeeNumber>804-685</EmployeeNumber> <LoanNumber>100002</LoanNumber> <PaymentAmount>415.25</PaymentAmount> <Balance>24499.75</Balance> </Payment> <Payment> <ReceiptNumber>100004</ReceiptNumber> <PaymentDate>2014-09-30</PaymentDate> <EmployeeNumber>804-685</EmployeeNumber> <LoanNumber>100003</LoanNumber> <PaymentAmount>102.12</PaymentAmount> <Balance>2961.31</Balance> </Payment> <Payment> <ReceiptNumber>100005</ReceiptNumber> <PaymentDate>2014-10-02</PaymentDate> <EmployeeNumber>492-947</EmployeeNumber> <LoanNumber>100001</LoanNumber> <PaymentAmount>249.08</PaymentAmount> <Balance>8219.51</Balance> </Payment> <Payment> <ReceiptNumber>100006</ReceiptNumber> <PaymentDate>2014-10-26</PaymentDate> <EmployeeNumber>429-374</EmployeeNumber> <LoanNumber>100002</LoanNumber> <PaymentAmount>415.25</PaymentAmount> <Balance>24084.5</Balance> </Payment> <Payment> <ReceiptNumber>100007</ReceiptNumber> <PaymentDate>2014-10-26</PaymentDate> <EmployeeNumber>836-486</EmployeeNumber> <LoanNumber>100003</LoanNumber> <PaymentAmount>102.12</PaymentAmount> <Balance>2859.19</Balance> </Payment> <Payment> <ReceiptNumber>100008</ReceiptNumber> <PaymentDate>2014-10-30</PaymentDate> <EmployeeNumber>836-486</EmployeeNumber> <LoanNumber>100001</LoanNumber> <PaymentAmount>249.08</PaymentAmount> <Balance>7970.43</Balance> </Payment> <Payment> <ReceiptNumber>100009</ReceiptNumber> <PaymentDate>2014-11-25</PaymentDate> <EmployeeNumber>804-685</EmployeeNumber> <LoanNumber>100002</LoanNumber> <PaymentAmount>415.25</PaymentAmount> <Balance>23669.25</Balance> </Payment> <Payment> <ReceiptNumber>100010</ReceiptNumber> <PaymentDate>2014-11-28</PaymentDate> <EmployeeNumber>836-486</EmployeeNumber> <LoanNumber>100004</LoanNumber> <PaymentAmount>573.44</PaymentAmount> <Balance>33832.91</Balance> </Payment> <Payment> <ReceiptNumber>100011</ReceiptNumber> <PaymentDate>2014-12-12</PaymentDate> <EmployeeNumber>836-486</EmployeeNumber> <LoanNumber>100001</LoanNumber> <PaymentAmount>498.16</PaymentAmount> <Balance>7472.27</Balance> </Payment> <Payment> <ReceiptNumber>100012</ReceiptNumber> <PaymentDate>2014-12-12</PaymentDate> <EmployeeNumber>240-750</EmployeeNumber> <LoanNumber>100001</LoanNumber> <PaymentAmount>25</PaymentAmount> <Balance>7447.27</Balance> </Payment> <Payment> <ReceiptNumber>100013</ReceiptNumber> <PaymentDate>2014-12-25</PaymentDate> <EmployeeNumber>492-947</EmployeeNumber> <LoanNumber>100001</LoanNumber> <PaymentAmount>249.08</PaymentAmount> <Balance>7223.19</Balance> </Payment> <Payment> <ReceiptNumber>100014</ReceiptNumber> <PaymentDate>2014-12-31</PaymentDate> <EmployeeNumber>804-685</EmployeeNumber> <LoanNumber>100002</LoanNumber> <PaymentAmount>415.25</PaymentAmount> <Balance>23254</Balance> </Payment> <Payment> <ReceiptNumber>100015</ReceiptNumber> <PaymentDate>2014-12-31</PaymentDate> <EmployeeNumber>836-486</EmployeeNumber> <LoanNumber>100003</LoanNumber> <PaymentAmount>204.24</PaymentAmount> <Balance>2654.95</Balance> </Payment> </Payments>
Lambda Square Apartments: payments.aspx
<%@ Page Language="VB" %> <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Xml" %> <!DOCTYPE html> <html> <head runat="server"> <title>Watts A Loan - Loans Payments</title> </head> <body> <h3>Watts A Loan - Loans Payments</h3> <% Dim strEmployee As String Dim strPaymentsFile = Server.MapPath("payments.xml") Dim strEmployeesFile = Server.MapPath("employees.xml") Dim xnlEmployees, xnlPayments As XmlNodeList Dim xdPayments, xdEmployees As New XmlDocument() If File.Exists(strPaymentsFile) Then Using fsPayments As New FileStream(strPaymentsFile, FileMode.Open, FileAccess.Read) xdPayments.Load(fsPayments) xnlPayments = xdPayments.DocumentElement.ChildNodes Response.Write("<table border=1><tr><td><b>Receipt #</b></td>") Response.Write("<td><b>Pmt Date</b></td>") Response.Write("<td><b>Processed By</b></td>") Response.Write("<td><b>Loan Number</b></td>") Response.Write("<td><b>Payment Amount</b></td>") Response.Write("<td><b>Balance</b></td></tr>") For i = 0 To xnlPayments.Count - 1 Response.Write("<td>" & xnlPayments(i).ChildNodes(0).InnerText & "</td>") ' Receipt Number Response.Write("<td>" & xnlPayments(i).ChildNodes(1).InnerText & "</td>") ' Payment Date strEmployee = xnlPayments(i).ChildNodes(2).InnerText If File.Exists(strEmployeesFile) Then Using fsEmployees As New FileStream(strEmployeesFile, FileMode.Open, FileAccess.Read) xdEmployees.Load(fsEmployees) xnlEmployees = xdEmployees.DocumentElement.ChildNodes For j As Integer = 0 To xnlEmployees.Count - 1 If xnlEmployees(j).ChildNodes(0).InnerText = xnlPayments(i).ChildNodes(2).InnerText Then strEmployee &= ": " & xnlEmployees(j).ChildNodes(1).InnerText & " " & xnlEmployees(j).ChildNodes(2).InnerText Exit For End If Next End Using End If Response.Write("<td>" & strEmployee & "</td>") ' Employee Response.Write("<td>" & xnlPayments(i).ChildNodes(3).InnerText & "</td>") ' Loan Number Response.Write("<td>" & FormatNumber(xnlPayments(i).ChildNodes(4).InnerText) & "</td>") ' Payment Amount Response.Write("<td>" & FormatNumber(xnlPayments(i).ChildNodes(5).InnerText) & "</td></tr>") ' Balance Next Response.Write("</table>") End Using End If %> </body> </html>
This would produce:
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.
If the node has more than one child with the same name, the property would return the first child with that name. Here is an example:
Solo Music Store: StoreItems.xml
<?xml version="1.0" encoding="UTF-8"?> <store-items> <store-item> <item-number>930485</item-number> <category>Keyboards</category> <sub-category>Synthesizers</sub-category> <item-name>Roland JUNO-Gi Synthesizer</item-name> <unit-price>780</unit-price> </store-item> <store-item> <item-number>485948</item-number> <category>Drums</category> <sub-category>Acoustic Drum Sets</sub-category> <item-name>Sound Percussion Complete 5-Piece Drum Set with Cymbals & Hardware</item-name> <unit-price>350</unit-price> </store-item> <store-item> <item-number>920820</item-number> <category>Miscellaneous</category> <sub-category>DJ Accessories</sub-category> <item-name>Pioneer RMX-1000 Remix Station Black</item-name> <unit-price>650</unit-price> </store-item> <store-item> <item-number>406033</item-number> <category>Guitars</category> <sub-category>Electric Guitars</sub-category> <item-name>B.C. Rich Pro X Custom Special X3 Mockingbird Electric Guitar Tobacco Burst</item-name> <unit-price>395.95</unit-price> </store-item> <store-item> <item-number>358460</item-number> <category>Bass</category> <sub-category>Electric Basses</sub-category> <item-name>Fender Deluxe P Bass Special 4-String Bass</item-name> <unit-price>695.95</unit-price> </store-item> <store-item> <item-number>724799</item-number> <category>Accessories</category> <sub-category>Cables</sub-category> <item-name>Monster Cable S-100 XLR Microphone Cable</item-name> <unit-price>14</unit-price> </store-item> <store-item> <item-number>582693</item-number> <category>Keyboards</category> <sub-category>Organs</sub-category> <item-name>Roland VK-88 Combo Organ</item-name> <unit-price>5695</unit-price> </store-item> <store-item> <item-number>350250</item-number> <category>Guitars</category> <sub-category>Acoustic Guitars</sub-category> <item-name>FA-100 Acoustic</item-name> <unit-price>120</unit-price> </store-item> <store-item> <item-number>332085</item-number> <category>Miscellaneous</category> <sub-category>Multitrack Recorders</sub-category> <item-name>Zoom R8 8-Track SD Recorder, Sampler & USB Interface</item-name> <unit-price>295.75</unit-price> </store-item> <store-item> <item-number>836360</item-number> <category>Brass Instruments</category> <sub-category>Trumpets</sub-category> <item-name>Brasswind Model II Student Bb Trumpet</item-name> <unit-price>180</unit-price> </store-item> <store-item> <item-number>415158</item-number> <category>Drums</category> <sub-category>Electronic Drum Sets</sub-category> <item-name>Simmons SD5X Electronic Drum Set</item-name> <unit-price>425.75</unit-price> </store-item> <store-item> <item-number>886182</item-number> <category>Keyboards</category> <sub-category>Synthesizers</sub-category> <item-name>Roland Jupiter-80 Synthesizer</item-name> <unit-price>3525</unit-price> </store-item> <store-item> <item-number>516080</item-number> <category>Guitars</category> <sub-category>Acoustic-Electric Guitars</sub-category> <item-name>Taylor 214ce Rosewood/Spruce Grand Auditorium Acoustic-Electric Guitar</item-name> <unit-price>1000</unit-price> </store-item> <store-item> <item-number>536949</item-number> <category>Live Sound</category> <sub-category>Packages</sub-category> <item-name>Phonic Powerpod 620 Plus / S710 PA Package</item-name> <unit-price>295.95</unit-price> </store-item> <store-item> <item-number>414913</item-number> <category>Woodwinds</category> <sub-category>Saxophones</sub-category> <item-name>Allora Vienna Series Intermediate Alto Saxophone</item-name> <unit-price>795.95</unit-price> </store-item> <store-item> <item-number>161553</item-number> <category>Miscellaneous</category> <sub-category>Multitrack Recorders</sub-category> <item-name>TASCAM DP-32 Digital 32-Track Portastudio</item-name> <unit-price>795.95</unit-price> </store-item> <store-item> <item-number>355862</item-number> <category>Guitars</category> <sub-category>Electric Guitars</sub-category> <item-name>PRS SE Custom 24 Electric Guitar</item-name> <unit-price>595.85</unit-price> </store-item> <store-item> <item-number>293488</item-number> <category>Bass</category> <sub-category>Electric Basses</sub-category> <item-name>Ibanez SR1206E 6-String Electric Bass Vintage</item-name> <unit-price>1250</unit-price> </store-item> <store-item> <item-number>330088</item-number> <category>Keyboards</category> <sub-category>Synthesizers</sub-category> <item-name>Korg MicroKORG Synthesizer/Vocoder</item-name> <unit-price>415.55</unit-price> </store-item> <store-item> <item-number>115599</item-number> <category>Accessories</category> <sub-category>Cables</sub-category> <item-name>Right-On Cable</item-name> <unit-price>98.95</unit-price> </store-item> <store-item> <item-number>402882</item-number> <category>Accessories</category> <sub-category>Cables</sub-category> <item-name>Monster Cable Digilink 5 Pin MIDI Cable</item-name> <unit-price>9.95</unit-price> </store-item> <store-item> <item-number>937528</item-number> <category>Guitars</category> <sub-category>Electric Guitars</sub-category> <item-name>ESP LTD EC-256FM Electric Guitar</item-name> <unit-price>395.95</unit-price> </store-item> <store-item> <item-number>355582</item-number> <category>Miscellaneous</category> <sub-category>Speakers</sub-category> <item-name>Peavey PR 12 Speaker Pair</item-name> <unit-price>360</unit-price> </store-item> <store-item> <item-number>140864</item-number> <category>Brass Instruments</category> <sub-category>Trombones</sub-category> <item-name>Allora Student Series Bb Trombone Model AATB-102</item-name> <unit-price>215.5</unit-price> </store-item> <store-item> <item-number>173031</item-number> <category>Drums</category> <sub-category>Hi-Hat Cymbals</sub-category> <item-name>Zildjian ZXT Solid Hi-Hat Cymbal (Pair) 14 Inches</item-name> <unit-price>145.75</unit-price> </store-item> <store-item> <item-number>217790</item-number> <category>Live Sound</category> <sub-category>Microphones</sub-category> <item-name>MXL 3000 Mic Bundle</item-name> <unit-price>245.85</unit-price> </store-item> <store-item> <item-number>676184</item-number> <category>Keyboards</category> <sub-category>Pianos</sub-category> <item-name>Williams Overture 88 Key Digital Piano</item-name> <unit-price>595.95</unit-price> </store-item> <store-item> <item-number>406266</item-number> <category>Live Sound</category> <sub-category>Microphones</sub-category> <item-name>MXL V63M Condenser Studio Microphone</item-name> <unit-price>99.95</unit-price> </store-item> <store-item> <item-number>357020</item-number> <category>Drums</category> <sub-category>Acoustic Drum Sets</sub-category> <item-name>Ludwig Breakbeats by Questlove 4-Piece Shell Pack Azure Sparkle</item-name> <unit-price>395.95</unit-price> </store-item> <store-item> <item-number>486021</item-number> <category>Keyboards</category> <sub-category>Synthesizers</sub-category> <item-name>Roland BK-9 Backing Keyboard</item-name> <unit-price>2495.85</unit-price> </store-item> <store-item> <item-number>686659</item-number> <category>Bass</category> <sub-category>Electric Basses</sub-category> <item-name>Fender American Deluxe Jazz Bass V 5-String Electric Bass</item-name> <unit-price>1795.95</unit-price> </store-item> <store-item> <item-number>583746</item-number> <category>Guitars</category> <sub-category>Acoustic Guitars</sub-category> <item-name>Yamaha FG700S Folk Acoustic Guitar</item-name> <unit-price>225.5</unit-price> </store-item> <store-item> <item-number>388835</item-number> <category>Drums</category> <sub-category>Acoustic Drum Sets</sub-category> <item-name>Gretsch Drums Energy 5-Piece Drum Set with Hardware and Sabian SBR Cymbals</item-name> <unit-price>695.95</unit-price> </store-item> <store-item> <item-number>258395</item-number> <category>Accessories</category> <sub-category>Cables</sub-category> <item-name>Monster Cable Performer 500 Speaker Cable</item-name> <unit-price>21.5</unit-price> </store-item> <store-item> <item-number>769138</item-number> <category>Live Sound</category> <sub-category>Amplifiers</sub-category> <item-name>Acoustic Lead Guitar Series G120 DSP 120W Guitar Combo Amp</item-name> <unit-price>199.95</unit-price> </store-item> <store-item> <item-number>275157</item-number> <category>Keyboards</category> <sub-category>Synthesizers</sub-category> <item-name>Yamaha S90XS 88-Key Balanced Weighted Hammer Action Synthesizer</item-name> <unit-price>2450</unit-price> </store-item> <store-item> <item-number>843814</item-number> <category>Guitars</category> <sub-category>Acoustic Guitars</sub-category> <item-name>Fender CD100 12-String Acoustic Guitar Natural</item-name> <unit-price>255.5</unit-price> </store-item> <store-item> <item-number>281141</item-number> <category>Orchestra</category> <sub-category>Violins</sub-category> <item-name>Florea Recital II Violin Outfit</item-name> <unit-price>150</unit-price> </store-item> <store-item> <item-number>966060</item-number> <category>Drums</category> <sub-category>Electronic Drum Sets</sub-category> <item-name>Simmons SDXpress2 Compact 5-Piece Electronic Drum Kit</item-name> <unit-price>225.5</unit-price> </store-item> <store-item> <item-number>559606</item-number> <category>Live Sound</category> <sub-category>Packages</sub-category> <item-name>Gear One PA2400 / Kustom KPC15 Mains and Monitors Package</item-name> <unit-price>696.95</unit-price> </store-item> <store-item> <item-number>725504</item-number> <category>Miscellaneous</category> <sub-category>Mixers</sub-category> <item-name>Nady PMX-1600 16 Channel/4 Bus Powered Mixer w/DSP Effects</item-name> <unit-price>649.95</unit-price> </store-item> <store-item> <item-number>972405</item-number> <category>Guitars</category> <sub-category>Electric Guitars</sub-category> <item-name>ESP LTD EC-256FM Electric Guitar</item-name> <unit-price>395.95</unit-price> </store-item> <store-item> <item-number>434426</item-number> <category>Keyboards</category> <sub-category>Pianos</sub-category> <item-name>Suzuki S-350 Mini Grand Digital Piano</item-name> <unit-price>2500</unit-price> </store-item> <store-item> <item-number>259592</item-number> <category>Accessories</category> <sub-category>Cables</sub-category> <item-name>Mogami Gold Instrument Cable Angled - Straight Cable</item-name> <unit-price>42.25</unit-price> </store-item> <store-item> <item-number>382730</item-number> <category>Orchestra</category> <sub-category>Violins</sub-category> <item-name>Mendini 4/4 MV300 Solid Wood Violin in Satin Finish</item-name> <unit-price>59.95</unit-price> </store-item> <store-item> <item-number>849926</item-number> <category>Bass</category> <sub-category>Electric Basses</sub-category> <item-name>Squier by Fender Vintage Modified Jazz Bass ''77, Amber</item-name> <unit-price>325.5</unit-price> </store-item> <store-item> <item-number>207925</item-number> <category>Woodwinds</category> <sub-category>Saxophones</sub-category> <item-name>Yamaha YAS-62III Professional Alto Saxophone</item-name> <unit-price>2950</unit-price> </store-item> </store-items>
Solo Music Store: StoreItems.aspx
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Xml" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Solo Music Store</title>
</head>
<body>
<h3>Solo Music Store</h3>
<%
Dim xnStoreItem As XmlNode
Dim xeStoreItem As XmlElement
Dim xnlStoreItems As XmlNodeList
Dim xdStoreItems As New XmlDocument()
Dim strStoreItemsFile = Server.MapPath("StoreItems.xml")
xdStoreItems.Load(strStoreItemsFile)
xeStoreItem = xdStoreItems.DocumentElement
xnlStoreItems = xeStoreItem.ChildNodes
For Each xnStoreItem In xnlStoreItems
Response.Write("<br>" & xnStoreItem("item-name").InnerText)
Next
%>
</body>
</html>
Remember that every child node holds its own collection of nodes. As a result, you can access a child node of a node using its XML name. Here are examples:
<%@ Page Language="VB" %> <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Xml" %> <!DOCTYPE html> <html> <head runat="server"> <script runat="server"> Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load Dim i As Integer Dim xnlStoreItems As XmlNodeList Dim xdStoreItems As New XmlDocument() Dim strStoreItemsFile = Server.MapPath("StoreItems.xml") If Not IsPostBack Then If File.Exists(strStoreItemsFile) Then lblAvailableItems.Visible = False tblAvailableItems.Rows.Clear() xdStoreItems.Load(strStoreItemsFile) xnlStoreItems = xdStoreItems.DocumentElement.ChildNodes ' Display the categories in the left list box For i = 0 To xnlStoreItems.Count - 1 ' Make sure the list box doesn't yet have the category being added If Not lbxCategories.Items.Contains(New ListItem(xnlStoreItems(i)("category").InnerText)) Then lbxCategories.Items.Add(xnlStoreItems(i)("category").InnerText) End If Next ' pbxSelectedItem.Image = Image.FromFile("default.jpg") End If End If End Sub Private Sub lbxCategoriesSelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lbxCategories.SelectedIndexChanged Dim i As Integer Dim xnlStoreItems As XmlNodeList Dim xdStoreItems As New XmlDocument() Dim strStoreItemsFile = Server.MapPath("StoreItems.xml") If File.Exists(strStoreItemsFile) Then xdStoreItems.Load(strStoreItemsFile) xnlStoreItems = xdStoreItems.DocumentElement.ChildNodes lblAvailableItems.Visible = False lbxSubCategories.Items.Clear() For i = 0 To xnlStoreItems.Count - 1 If xnlStoreItems(i)("category").InnerText = lbxCategories.SelectedItem.Text Then If Not lbxSubCategories.Items.Contains(New ListItem(xnlStoreItems(i)("sub-category").InnerText)) Then lbxSubCategories.Items.Add(xnlStoreItems(i)("sub-category").InnerText) End If End If Next End If End Sub Private Sub lbxSubCategoriesSelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lbxSubCategories.SelectedIndexChanged Dim i As Integer Dim colStoreItem As TableCell Dim rowStoreItem As TableRow Dim xnlStoreItems As XmlNodeList Dim xdStoreItems As New XmlDocument() Dim strStoreItemsFile = Server.MapPath("StoreItems.xml") If File.Exists(strStoreItemsFile) Then xdStoreItems.Load(strStoreItemsFile) xnlStoreItems = xdStoreItems.DocumentElement.ChildNodes lblAvailableItems.Visible = True colStoreItem = New TableCell() colStoreItem.Text = "<b>Item #</b>" rowStoreItem = New TableRow() rowStoreItem.Cells.Add(colStoreItem) colStoreItem = New TableCell() colStoreItem.Text = "<b>Item Name</b>" rowStoreItem.Cells.Add(colStoreItem) colStoreItem = New TableCell() colStoreItem.Text = "<b>Unit Price</b>" rowStoreItem.Cells.Add(colStoreItem) tblAvailableItems.Rows.Add(rowStoreItem) For i = 0 To xnlStoreItems.Count - 1 If xnlStoreItems(i)("sub-category").InnerText = lbxSubCategories.SelectedItem.Text Then rowStoreItem = New TableRow() colStoreItem = New TableCell() colStoreItem.Text = xnlStoreItems(i)("item-number").InnerText rowStoreItem.Cells.Add(colStoreItem) colStoreItem = New TableCell() colStoreItem.Text = xnlStoreItems(i)("item-name").InnerText rowStoreItem.Cells.Add(colStoreItem) colStoreItem = New TableCell() colStoreItem.Text = FormatNumber(xnlStoreItems(i)("unit-price").InnerText) rowStoreItem.Cells.Add(colStoreItem) tblAvailableItems.Rows.Add(rowStoreItem) End If Next End If End Sub </script> <title>Solo Music Store</title> </head> <body> <h3>Solo Music Store</h3> <form id="frmMusicStore" runat="server"> <div> <table> <tr> <td style="width: 100px"><b>Categories</b></td> <td><b>Sub-Categories</b></td> </tr> <tr> <td> <asp:ListBox id="lbxCategories" Width="145px" Height="181px" AutoPostBack="True" runat="server"></asp:ListBox> </td> <td> <asp:ListBox id="lbxSubCategories" Width="145px" Height="181px" AutoPostBack="True" runat="server"></asp:ListBox> </td> </tr> <tr> <td colspan="2"><asp:Label id="lblAvailableItems" Text="<b>Available Items</b>" Visible="False" runat="server"></asp:Label></td> </tr> <tr> <td colspan="2"> <asp:Table id="tblAvailableItems" Width="660px" GridLines="Both" CellPadding="4" CellSpacing="0" runat="server" > </asp:Table> </td> </tr> </table> </div> </form> </body> </html>
Locating an Element Using a Tag Name
Remember that the XmlDocument class has a method named GetElementByTagName that can be used to reach an element. Once reach a node of a particular name, you can perform an operation on it. For example, you can look for a particular node that holds a text of your choice. Here is an example:
Fun Department Store: UpdateStoreItem.aspx
<!DOCTYPE html> <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Xml" %> <html> <head runat="server"> <script runat="server"> Sub btnFindClick(ByVal sender As Object, ByVal e As EventArgs) Dim xnStoreItem As XmlNode Dim xnlStoreItems As XmlNodeList Dim xdStoreItems As New XmlDocument() Dim strStoreItemsFile = Server.MapPath("StoreItems1.xml") If String.IsNullOrEmpty(txtItemNumber.Text) Then Exit Sub End If If File.Exists(strStoreItemsFile) Then xdStoreItems.Load(strStoreItemsFile) xnlStoreItems = xdStoreItems.GetElementsByTagName("ItemNumber") For Each xnStoreItem In xnlStoreItems If xnStoreItem.InnerText = txtItemNumber.Text Then txtManufacturer.Text = xnStoreItem.NextSibling.InnerText txtCategory.Text = xnStoreItem.NextSibling.NextSibling.InnerText txtSubCategory.Text = xnStoreItem.NextSibling.NextSibling.NextSibling.InnerText txtItemName.Text = xnStoreItem.NextSibling.NextSibling.NextSibling.NextSibling.InnerText txtItemSize.Text = xnStoreItem.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText txtUnitPrice.Text = xnStoreItem.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.InnerText End If Next End If End Sub </script> <title>FunDS: Store Item Editor</title> </head> <body> <div align="center"> <h2>FunDS: Store Item Editor</h2> <form id="frmStoreItem" runat="server"> <table> <tr> <td>Item #:</td> <td><asp:TextBox id="txtItemNumber" runat="server"></asp:TextBox> <asp:Button runat="server" id="btnFind" Text="Find" OnClick="btnFindClick"></asp:Button></td> </tr> <tr> <td>Manufacturer:</td> <td><asp:TextBox id="txtManufacturer" runat="server"></asp:TextBox> </td> </tr> <tr> <td>Category:</td> <td><asp:TextBox id="txtCategory" runat="server"></asp:TextBox></td> </tr> <tr> <td>Sub-Category:</td> <td><asp:TextBox id="txtSubCategory" runat="server"></asp:TextBox></td> </tr> <tr> <td>Item Name:</td> <td><asp:TextBox id="txtItemName" runat="server"></asp:TextBox> </td> </tr> <tr> <td>Item Size:</td> <td><asp:TextBox id="txtItemSize" runat="server"></asp:TextBox></td> </tr> <tr> <td>Unit Price:</td> <td><asp:TextBox id="txtUnitPrice" runat="server"></asp:TextBox></td> </tr> </table> </form> </div> </body> </html>
|
||
Previous | Copyright © 2002-2016 FunctionX | Next |
|