1. Trang chủ
  2. » Công Nghệ Thông Tin

XML Step by Step- P20 ppsx

15 190 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 15
Dung lượng 341,93 KB

Nội dung

Chapter 10 Displaying XML Documents Using Data Binding 351 10 Data Binding <BUTTON ONCLICK='FindBooks()'>Search</BUTTON> <HR> Results:<P> <DIV ID=ResultDiv></DIV> <SCRIPT LANGUAGE="JavaScript"> function FindBooks () { SearchString = SearchText.value.toUpperCase(); if (SearchString == "") { ResultDiv.innerHTML = "&ltYou must enter text into " + "'Title text' box.&gt"; return; } dsoInventory.recordset.moveFirst(); ResultHTML = ""; while (!dsoInventory.recordset.EOF) { TitleString = dsoInventory.recordset("TITLE").value; if (TitleString.toUpperCase().indexOf(SearchString) >=0) ResultHTML += "<I>" + dsoInventory.recordset("TITLE") + "</I>, " + "<B>" + dsoInventory.recordset("AUTHOR") + "</B>, " + dsoInventory.recordset("BINDING") + ", " + dsoInventory.recordset("PAGES") + " pages, " + dsoInventory.recordset("PRICE") + "<P>"; dsoInventory.recordset.moveNext(); } 352 XML Step by Step if (ResultHTML == "") ResultDiv.innerHTML = "&ltno books found&gt"; else ResultDiv.innerHTML = ResultHTML; } </SCRIPT> </BODY> </HTML> Listing 10-13. The HTML page displays a TEXT type INPUT element, which lets the user en- ter a single line of search text: <INPUT TYPE=”TEXT” ID=”SearchText”> The page also displays a BUTTON element labeled “Search”: <BUTTON ONCLICK=’FindBooks()’>Search</BUTTON> When the user clicks the button, the FindBooks script function is called, which extracts the search text from the INPUT element, searches the titles of all BOOK records in the XML document for the text, and then displays the matching BOOK records, as shown here: The script function FindBooks is contained in its own SCRIPT element and is written in JScript: 354 XML Step by Step tip JScript is Microsoft’s version of the generic JavaScript scripting language. (In the example SCRIPT block, the LANGUAGE attribute gives the generic language name.) For information on JScript and other Microsoft Web scripting technologies, see the topic “Scripting” in the MSDN Library on the Web at http://msdn.microsoft.com/library/. The FindBooks function begins by obtaining the text currently entered into the INPUT element (which has the ID SearchText), and then using the JScript method toUpperCase to convert the text to uppercase. (FindBooks converts all text to uppercase so that the search will be case-insensitive.) SearchString = SearchText.value.toUpperCase(); If the user hasn’t entered anything into the INPUT, the function displays a mes- sage and exits: if (SearchString == "") { ResultDiv.innerHTML = "&ltYou must enter text into " + "'Title text' box.&gt"; return; } ResultDiv is the ID of a DIV element at the bottom of the page that displays the search results. Assigning text (which can include HTML markup) to its innerHTML property causes the DIV to display that text (and to render any HTML markup it contains). The function then makes the first XML record current, using the recordset.moveFirst method that you’ve seen before: dsoInventory.recordset.moveFirst(); Next it blanks the string variable used to store the HTML for the search results (ResultHTML): ResultHTML = “”; Now FindBooks enters a loop that moves through all records in the XML docu- ment. It uses the recordset.EOF property to stop the loop when end-of-file is reached, and it uses recordset.moveNext to move to each new record: Chapter 10 Displaying XML Documents Using Data Binding 355 10 Data Binding while (!dsoInventory.recordset.EOF) { TitleString = dsoInventory.recordset("TITLE").value; if (TitleString.toUpperCase().indexOf(SearchString) >=0) ResultHTML += "<I>" + dsoInventory.recordset("TITLE") + "</I>, " + "<B>" + dsoInventory.recordset("AUTHOR") + "</B>, " + dsoInventory.recordset("BINDING") + ", " + dsoInventory.recordset("PAGES") + " pages, " + dsoInventory.recordset("PRICE") + "<P>"; dsoInventory.recordset.moveNext(); } The loop first obtains the value of the TITLE field in the current record: TitleString = dsoInventory.recordset(“TITLE”).value; The expression on the right of the equal sign is a shorthand notation for calling the fields property of the recordset object. Here’s the full notation: TitleString = dsoInventory.recordset.fields(“TITLE”).value; The fields property contains a collection of all the fields belonging to the current record. You access a particular field by placing its name in parentheses ("TITLE" in the example), and you obtain the content of this field as a string by appending the value property. The loop then uses the JScript method indexOf to determine whether the current record’s title contains the search text. If the loop finds the search text, the code inside the if statement appends to the ResultHTML string the text and HTML markup required to display the current record: 356 XML Step by Step if (TitleString.toUpperCase().indexOf(SearchString) >=0) ResultHTML += "<I>" + dsoInventory.recordset("TITLE") + "</I>, " + "<B>" + dsoInventory.recordset("AUTHOR") + "</B>, " + dsoInventory.recordset("BINDING") + ", " + dsoInventory.recordset("PAGES") + " pages, " + dsoInventory.recordset("PRICE") + "<P>"; Once the loop has exited, the function assigns the HTML markup containing the results to the innerHTML property of the DIV element in the BODY of the document that is used to display these results (this DIV element has the identi- fier ResultDiv): if (ResultHTML == "") ResultDiv.innerHTML = "&ltno books found&gt"; else ResultDiv.innerHTML = ResultHTML; The DIV element immediately renders the HTML markup and displays the results. 357 Displaying XML Documents Using Document Object Model Scripts In the previous chapter, you learned about the Data Source Object (DSO) programming model, which lets you use either data binding or a script to display an XML document from within an HTML page. The DSO stores the XML data as a record set, and is thus suitable primarily for displaying those XML documents structured as symmetrical record sets. In this chapter, you’ll learn about an entirely different programming model known as the XML Document Object Model, or DOM. The DOM consists of a set of programming objects that represent the different components of an XML document. The properties and methods of these objects let you use scripts to dis- play the XML document from within an HTML page. Although the DOM re- quires a bit more work than the DSO (for example, it doesn’t allow the simple technique of data binding), it stores the XML data in a hierarchical, treelike data structure that mirrors the hierarchical structure of the XML document. You can thus use the DOM to display any type of XML document—whether or not it’s structured as a record set—and you can use it to access any component of an XML document, including elements, attributes, processing instructions, comments, and entity and notation declarations. Document Object Model Scripts CHAPTER 11 Chapter 11 Displaying XML Documents Using Document Object Model Scripts 359 11 Document Object Model Scripts Linking the XML Document to the HTML Page To access an XML document using the DOM, you must link the XML docu- ment to the HTML page. The easiest way to do this is to insert a data island. Recall that you create a data island by using an HTML element named XML. For example, the following BODY element of an HTML page includes a data island that links the XML document contained in the file Book.xml: <BODY> <XML ID="dsoBook” SRC="Book.xml"></XML> <! other elements in body of page > </BODY> For more information on data islands, see “The First Step: Linking the XML Document to the HTML Page” in Chapter 10. As you learned in Chapter 10, the ID that you assign to the data island refers to the document’s DSO. You use the XMLDocument member of the DSO to access the DOM, as shown in this line of script code: Document = dsoBook.XMLDocument; Specifically, the XMLDocument member contains the root object of the DOM, known as the Document node. You’ll use the Document node to access all the other DOM objects. Thus, adding a data island to an HTML page causes Internet Explorer to create both a DSO (represented directly by the data island’s ID) and a DOM (accessed through the DSO’s XMLDocument member). tip If you want to access more than one XML document from an HTML page, you can insert a data island for each. You can even include more than one data is- land for a single XML document. (The latter technique might be useful for maintaining several different versions of the XML data if your page modifies the contents of the DOM data cached in memory. This chapter, however, doesn’t cover the techniques for modifying DOM data.) 360 XML Step by Step note When you open an XML document through a data island in an HTML page, Internet Explorer checks the document for well-formedness and also—if the document includes a document type declaration—for validity. If the document contains an error, the DOM nodes will be empty of data and a DOM script will fail in its attempt to display the XML data. However, you won’t see a message indicating the specific error in the XML document. To see a helpful description of any well-formedness or validity error in the linked XML document, you can test that document using one of the validity testing pages presented in “Check- ing an XML Document for Validity” on page 396. The Structure of the DOM In the DOM, the programming objects that represent the XML document are known as nodes. When Internet Explorer processes a linked XML document and stores it within a DOM, it creates a node for each of the basic components of the XML document, such as the elements, attributes, and processing instructions. The DOM uses different types of nodes to represent different types of XML components. For example, an element is stored in an Element node and an attribute in an Attribute node. Table 11-1 lists the most important of these node types. Node type XML document Node name Node value component that the ( nodeName ( nodeValue node object represents property) property) Document The entire XML document #document null (This is the root node of the DOM node hierarchy. It’s used to access all other nodes.) Element An element Element type null (any name (for character data example, contained in the BOOK) element is in one or more child Text nodes) continued 362 XML Step by Step note In the Microsoft XML DOM documentation (cited in the Tip on page 356), each of the node names listed in the first column of Table 11-1 is prefaced with IXMLDOM—for example, IXMLDOMDocument, IXMLDOMElement, and IXMLDOMText. (These are the names of the programming interfaces for each node type.) Note also that the common node properties and methods (described later in this chapter) are listed under the name IXMLDOMNode. You can obtain each of the node names (listed in the third column) from the node’s nodeName property. The names beginning with a # character are stan- dard names for nodes representing XML components not named in the docu- ment. (For example, a comment is not given a name in an XML document. Therefore, the DOM uses the standard name #comment.) The other node names derive from the names assigned to the corresponding components in the XML document. (For example, the Element node representing an element of type BOOK would also be named BOOK.) You can obtain each of the node values (listed in the last column) from the node’s nodeValue property. Notice that for certain types of nodes (namely, Document, Element, DocumentType, Entity, and Notation nodes), nodeValue is always set to null, indicating that a node of that type doesn’t have a value (either because the corresponding document component doesn’t have a value, or because the DOM stores the component’s value in a child Text or Attribute node). You’ll learn more about many of the node types listed in Table 11-1 later in the chapter. note For a type of node that has a value, such as an Attribute node, if the correspond- ing document component contains no text (for instance, an attribute is assigned an empty string), nodeValue is set to an empty string, not to null. The DOM organizes the XML document’s nodes in a treelike hierarchical structure that mirrors the hierarchical structure of the document itself. It creates a single Document node that represents the entire XML document and serves as the root of this hierarchy. Note that the logical hierarchical structure of the XML elements, of which the document element is the root, is only a branch of the hierarchical structure of DOM nodes, which encompasses the entire document. Chapter 11 Displaying XML Documents Using Document Object Model Scripts 363 11 Document Object Model Scripts Consider, for instance, the example XML document in Listing 11-1. (You’ll find a copy of this listing on the companion CD under the filename Inventory Dom.xml.) This document contains an XML declaration, a comment, and a root element that includes child elements as well as attributes. The following figure shows the hierarchical organization of the nodes that the DOM creates to repre- sent this document. For each component of the example document, the figure indicates the type of node used to represent the component (for example, Docu- ment, Comment, and Element) as well as the node’s name (given in parenthe- ses—for example, #document, #comment, and INVENTORY). CommentProcessingInstruction Document Attribute Element (BOOK) Element (INVENTORY) Element (BOOK) Element (AUTHOR) TextText Text Attribute Element (TITLE) Element (PAGES) Element (PRICE) Element (BOOK) Element (AUTHOR) TextText Text Element (TITLE) Element (PAGES) Element (PRICE) Element (AUTHOR) TextText TextTextAttribute Element (TITLE) Element (PAGES) Element (PRICE) TextAttribute TextAttribute xml () #comment () version () #text () #text () #text () #text () #text () #text () #text () #text () Born () Born () #text () Born () #text () #text () #text () #document () Binding () Attribute Binding () Attribute Binding () [...]... document containing this node 11 Element.nodeName; 366 XML Step by Step continued Property Description Example text The entire text content of this node and of all descendent Element nodes The entire XML content of this node and all its descendent nodes AllCharacterData = Element.text; xml XMLContent = Element .xml; Table 11-2 Useful common properties provided by all node types Besides the common properties...364 XML Step by Step Inventory Dom .xml < ?xml version="1.0"?> .xml > The Adventures of Huckleberry Finn Mark Twain 298... and Displaying XML Document Elements In this section, you’ll learn the basic techniques for using an HTML page and the DOM to display the contents of an XML document’s elements Listings 11-2 and 11-3 demonstrate these techniques (You’ll find copies of these listings on the companion CD under the filenames Book .xml and DomDemo Fixed.htm.) Book .xml < ?xml version="1.0"?> .xml > DomDemo... containing the text “File Name: Inventory Dom .xml (This code is explained later in the chapter.) Chapter 11 Displaying XML Documents Using Document Object Model Scripts 367 In the previous section, you saw how to access the root Document node through the XMLDocument member of the DSO obtained from the XML data island The Document node is the gateway to the XML document You use it to access all other... Model Scripts 369 Listing 11-3 contains an HTML page that displays the content of each of the child elements in the XML document Here’s how this page looks in Internet Explorer: The XML document is linked to the page through the following data island: < /XML> The FOR="window" and EVENT="ONLOAD" attribute specifications cause the browser to execute the code in the SCRIPT... Document = dsoBook.XMLDocument; title.innerText= Document.documentElement.childNodes(0).text; author.innerText= Document.documentElement.childNodes(1).text; binding.innerText= Document.documentElement.childNodes(2).text; pages.innerText= Document.documentElement.childNodes(3).text; price.innerText= Document.documentElement.childNodes(4).text; 11 The page displays the XML document by means of the... FOR="window" EVENT="ONLOAD"> Document = dsoBook.XMLDocument; title.innerText= Document.documentElement.childNodes(0).text; Document Object Model Scripts Listing 11-2 11 The Adventures of Huckleberry Finn Mark Twain mass market paperback 298 $5.49 Chapter 11 Displaying XML Documents Using Document Object Model... $10.95 Moby-Dick Herman Melville 724 $9.95 Listing 11-1 Each node, as a programming object, provides properties and methods that let you access, display, manipulate, and obtain information on the corresponding XML component For example, for some types of nodes the nodeName... property will contain the value null if that property doesn’t apply to the particular node For example, if a node represents a type of XML component that can’t have attributes (such as a Document or Comment node) its attributes property will be null If a node represents a type of XML component that doesn’t have a data type (only certain attributes have a data type), its dataType property will be null If a... working with nodes in general Table 11-2 lists some of the more useful common properties You’ll find more information and examples for many of these properties later in the chapter Chapter 11 Displaying XML Documents Using Document Object Model Scripts 365 Property Description Example attributes A NamedNodeMap collection of all this node’s Attribute child nodes (or null if the node type can’t have Attribute . TextAttribute xml () #comment () version () #text () #text () #text () #text () #text () #text () #text () #text () Born () Born () #text () Born () #text () #text () #text () #document () Binding () Attribute Binding () Attribute Binding () 364 XML Step by Step Inventory Dom .xml < ?xml version="1.0"?> <! File Name: Inventory Dom .xml > <INVENTORY> <BOOK Binding="mass. node) continued 366 XML Step by Step Property Description Example text The entire text content of AllCharacterData = Element.text; this node and of all descendent Element nodes xml The entire XML content XMLContent. nodes) continued 362 XML Step by Step note In the Microsoft XML DOM documentation (cited in the Tip on page 356), each of the node names listed in the first column of Table 11-1 is prefaced with IXMLDOM—for

Ngày đăng: 03/07/2014, 07:20