12.3 Workwiththe XML DocumentObjectModel
I want to have more control over theXMLdocument as I create it. I heard that I can do
this withXML DOM. How do I workwiththe XML DocumentObject Model?
Technique
In How-Tos 12.1 and 12.2, you saw two ways to independently read and write XML
documents. However, what if you want to do both at the same time? To have this kind of
flexibility, you need to use the XML DocumentObject Model, also known as DOM.
The DOM class is an XMLdocument that is represented in memory. It allows you not
only to programmatically read and write out XML documents, but also to modify those
documents in memory.
Within the DOM, the XMLNode object is the base object in the DOM Tree,
XMLDocument class that extends it. XMLDocument has methods that allow you to
perform operations on thedocument as a whole. It also lets the developer workwiththe
nodes in the entire XML document.
Both XMLNode and XMLDocument have performance and usability enhancements over
prior versions.
The properties and methods of XMLNode and XMLDocument that will be used for this
How-To are listed in Table 12.6.
Table 12.6. DOM Properties and Methods Used in This How-To
Class Name Property/Method Purpose/Description
XMLDocument LoadXML Loads an XMLdocument into the XMLDocument
object. In this case, it is a means to create the stub
for theXMLdocument that will be created from
the dataset.
XMLDocument DocumentElement Serves as the root element for the document. It is,
in fact, of the type XMLElement.
XMLDocument CreateNode Creates an XMLNode object.
XMLElement AppendChild Appends the node created to the element specified
as a child.
XMLDocument CreateComment Adds a comment to theXML document.
XMLNode AppendChild Appends a node to another node as a child.
XMLDocument Save Saves the current XML document.
Steps
Open and run the Visual Basic .NET-Chapter 12 solution. From the main Web page,
click on the hyperlink withthe caption How-To 12.3: Working withthe XML Document
Object Model. As with How-To 12.1, when the page loads, you can enter a few names.
Enter the last and first names, and then click the button labeled Add to DataTable. When
you have added a few names, click the button labeled Create XML File. Using Explorer,
open the file created in C:\ called test.xml(see Figure 12.3).
1. Create a Web Form. Then place the Labels, TextBoxes, Buttons, and DataGrid
objects as seen in Figure 12.3 on the form withthe properties set as in Table 12.7.
Table 12.7. Label, TextBox, and Button Control Property Settings
Object Property Setting
Label Text Last Name
TextBox ID txtLastName
Label Text First Name
TextBox ID txtFirstName
Button ID btnAdd
Text Add to DataTable
Button ID btnCreateXMLFile
Text Create XML File
DataGrid ID dgDataToWrite
HyperLink ID hplReturnToMain
NavigateURL wfrmMain.aspx
2. Add the following line to the code module of the form. I place it under the line that
reads Web Form Designer Generated Code.
3. Dim mdtData As New DataTable()
4. Add the code in Listing 12.6 to the Load event of the page. If the data table has not
been saved to the Session object, then it is created from scratch by first creating
the data columns and then adding them to the data table. The DataTable object is
then saved to the Session objectwiththe name MyDataTable. If the Session object
entry already exists, it is reassigned to the module variable mdtData. Last, the data
table is bound to the DataGrid object by calling the BindTheGrid routine, which is
described in the next step.
Listing 12.6 wfrmHowTo12_3.aspx.vb: Creating a DataTable Object from
Scratch
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
If (Session("MyDataTable") Is Nothing) Then
Dim dcFirstName As New DataColumn()
dcFirstName.ColumnName = "FirstName"
dcFirstName.Caption = "First Name"
mdtData.Columns.Add(dcFirstName)
Dim dcLastName As New DataColumn()
dcLastName.ColumnName = "LastName"
dcLastName.Caption = "Last Name"
mdtData.Columns.Add(dcLastName)
Session("MyDataTable") = mdtData
Else
mdtData = CType(Session("MyDataTable"), DataTable)
End If
BindTheGrid()
End Sub
5. Create the routine BindTheGrid, shown in Listing 12.7, in the code module for the
page.
Listing 12.7 wfrmHowTo12_3.aspx.vb: Binding the Data Table to the Data
Grid
Sub BindTheGrid()
dgDataToWrite.DataSource = mdtData
dgDataToWrite.DataBind()
End Sub
6. Add the code in Listing 12.8 to the Click event of the btnAdd button. This routine
starts off by calling the NewRow method off the mdtData data table, thus creating
a new DataRow object. The two columns in drNew are replaced withthe values in
txtLastName and txtFirstName. The new row is added to the data table, and the
text boxes are cleared. Last, mdtData is rebound to the data grid by calling
BindTheGrid.
Listing 12.8 wfrmHowTo12_3.aspx.vb: Adding Data to the Data Table and
Then Rebinding the Data Grid
Private Sub btnAdd_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnAdd.Click
Dim drNew As DataRow
drNew = mdtData.NewRow()
drNew.Item("LastName") = Me.txtLastName.Text
drNew.Item("FirstName") = Me.txtFirstName.Text
mdtData.Rows.Add(drNew)
Me.txtLastName.Text = ""
Me.txtFirstName.Text = ""
BindTheGrid()
End Sub
7. Add the code in Listing 12.9 to the Click event of the btnCreateXMLFile button.
After getting the number of rows in mdtData, an XMLdocument is started using
the LoadXML method. Next, the root element is retrieved so that nodes can then
be "hung" from it, using the CreateNode and AppendChild methods. A comment
is then added using the CreateComment method of xdMyData. Then, for each of
the rows in the mdtData, nodName is created using CreateNode and AppendChild
methods, and node on nodName is added for the LastName and FirstName. Again,
these nodes are added using the CreateNode and AppendChild methods. Last, the
Save method is used to save theXML document.
Listing 12.9 wfrmHowTo12_3.aspx.vb: Creating theXMLDocument
Private Sub btnCreateXMLFile_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnCreateXMLFile.Click
Dim xdMyData As New System.Xml.XmlDocument()
Dim xeRoot As System.Xml.XmlElement
Dim intCurrRow As Integer
Dim intNumRows As Integer
intNumRows = mdtData.Rows.Count - 1
With xdMyData
' Start theXMLdocument
.LoadXml("<?xml version='1.0' ?><Book></Book>")
xeRoot = .DocumentElement
Dim nodRoot As System.Xml.XmlNode = _
.CreateNode(System.Xml.XmlNodeType.Element, "Names", "")
xeRoot.AppendChild(nodRoot)
' Add the comment
.CreateComment("This file represents names list created using theXML
DOM")
For intCurrRow = 0 To intNumRows
' Start the current row
Dim nodName As System.Xml.XmlNode = _
.CreateNode(System.Xml.XmlNodeType.Element, "name", "")
nodName = nodRoot.AppendChild(nodName)
' Add the attributes (columns)
Dim nodFirstName As System.Xml.XmlNode = _
.CreateNode(System.Xml.XmlNodeType.Element, "FirstName",
"")
nodFirstName.InnerText =
mdtData.Rows(intCurrRow).Item("FirstName")
nodName.AppendChild(nodFirstName)
Dim nodLastName As System.Xml.XmlNode = _
.CreateNode(System.Xml.XmlNodeType.Element, "LastName",
"")
nodLastName.InnerText =
mdtData.Rows(intCurrRow).Item("LastName")
nodName.AppendChild(nodLastName)
Next
' Write theXML to file and close the writer
.Save("c:\Test.xml")
End With
End Sub
Figure 12.3. This XMLdocument was created using XMLTextWriter.
Comments
As you can see, working withthe DOM takes a bit more time and work. However, when
you really need to massage the data, this is the way to go!
. write out XML documents, but also to modify those
documents in memory.
Within the DOM, the XMLNode object is the base object in the DOM Tree,
XMLDocument. Purpose/Description
XMLDocument LoadXML Loads an XML document into the XMLDocument
object. In this case, it is a means to create the stub
for the XML document that