Work with the XML Document Object Model

Chia sẻ: Bui Tuan | Ngày: | Loại File: PDF | Số trang:7

lượt xem

Work with the XML Document Object Model

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Làm việc với các tài liệu XML Object Model Tôi muốn có kiểm soát nhiều hơn các tài liệu XML như tôi tạo ra nó. Tôi nghe nói rằng tôi có thể làm điều này với XML DOM. Làm thế nào để làm việc với các tài liệu XML Object Model?

Chủ đề:

Nội dung Text: Work with the XML Document Object Model

  1. 12.3 Work with the XML Document Object Model I want to have more control over the XML document as I create it. I heard that I can do this with XML DOM. How do I work with the XML Document Object 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 Document Object Model, also known as DOM. The DOM class is an XML document 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 the document as a whole. It also lets the developer work with the 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 XML document into the XMLDocument object. In this case, it is a means to create the stub for the XML document 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 the XML document.
  2. 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 with the caption How-To 12.3: Working with the 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 with the 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()
  3. 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 object with the 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.
  4. 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 with the 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 XML document 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
  5. 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 the XML document. Listing 12.9 wfrmHowTo12_3.aspx.vb: Creating the XML Document 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 the XML document .LoadXml("") 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 the XML 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 = _
  6. .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 the XML to file and close the writer .Save("c:\Test.xml") End With End Sub Figure 12.3. This XML document was created using XMLTextWriter.
  7. Comments As you can see, working with the DOM takes a bit more time and work. However, when you really need to massage the data, this is the way to go!
Đồng bộ tài khoản