XML and Internet Explorer

So far, we've seen that XML is about data, not the display of data. A logical question is then, How do I display XML data on my Web pages? Internet Explorer includes several objects that can be used when working with XML, the most common of which is the DOMDocument object. This object essentially acts as a middle layer between the data and the display portions of Internet Explorer.

When this object parses a document, it creates in memory a treelike structure of all the elements included in the document. It also provides access to the XML Document Object Model, an interface that allows access to the XML data. The object model exposes properties, methods, events, and the actual content (data) contained in the data tree. Details about the properties, methods, and events of the XML Document Object Model can be found later in this chapter in Tables 21-1 through 21-3. The object model lets authors view all parts of the tree, from roots to branches.

Code Listing 21-1 is a simple Web page that pulls data from an XML document and then displays it on screen. Figure 21-1 displays the results of this code.

Code Listing 21-1.

 <HTML> <HEAD> <TITLE>Code Listing 21-1</TITLE> <SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onload">   start() </SCRIPT> <SCRIPT LANGUAGE="JavaScript">   var xmlDoc=new ActiveXObject("Microsoft.XMLDOM")   xmlDoc.async=false   xmlDoc.load("email.xml") function start(){   var root=xmlDoc.documentElement   todata.innerText=root.childNodes.item(0).text   fromdata.innerText=root.childNodes.item(1).text   ccdata.innerText=root.childNodes.item(2).text   subjectdata.innerText=root.childNodes.item(3).text   bodydata.innerText=root.childNodes.item(4).text } </SCRIPT> </HEAD> <BODY>  <B>To:</B><SPAN ID="todata"></SPAN><BR>  <B>From:</B><SPAN ID="fromdata"></SPAN><BR>  <B>CC:</B><SPAN ID="ccdata"></SPAN><BR>  <B>Subject:</B><SPAN ID="subjectdata"></SPAN><BR>  <B>Body:</B><SPAN ID="bodydata"></SPAN><BR> </BODY> </HTML> 

Figure 21-1. A sample HTML page that has processed an XML document.

The first script block at the top of the HEAD is simply an event handler that calls the start function when the page has finished loading. We'll get to this function a little later. Note that the page itself contains SPAN tags that will be the eventual target of our XML data.

As mentioned earlier, the XML processor acts as the middle layer between the XML document and the HTML page (or any other application, for that matter). We need to load the XML processor as an object on our Web page so that we can interact with it through script.

 var xmlDoc=new ActiveXObject("Microsoft.XMLDOM") xmlDoc.async=false xmlDoc.load("email.xml") 

This code first loads the DOMDocument object and assigns it to the variable xmlDoc. This provides access to the XML processor and object model. The next line tells the processor not to load any documents asynchronously. This just means that the Web page will wait until the data in the document has been loaded before continuing. The value of true causes the data to be loaded in tandem with the rest of the page, meaning that some type of detection (usually testing the ondataavailable or onreadystatechange events or the readyState property) must be used to ensure that the data is loaded before it is used. The third line causes the object to load the XML file named email.xml, shown at the start of this chapter. The beginning of the data tree that is loaded can be represented as follows.

 DOCUMENT |---XMLDECL |   |---ATTRIBUTE version "1.0" +---ELEMENT EMAIL     |---ELEMENT TO     |   +---PCDATA "Bill_Pardi@hotmail.com" 

The tree begins with the Document object, which contains an XML declaration, and then the root element EMAIL. The EMAIL element contains further elements, of which the TO element is shown above. The value of the TO element is Bill_Pardi@hotmail.com, which is of the XML data type called PCDATA.

Once the page loads, the start function is called. This function is fairly straightforward. The first line of the function creates a variable named root and assigns to it the root node of the XML document. This gives us access to the base of the XML data tree. The next line of code assigns some text to the innerText property of the todata SPAN, which causes that text to display. The text it uses comes from the first child of the root XML element. It gets this text by accessing the first of the children of the root element with the code root.childNodes.item(0).text.

NOTE
If you understand this code, you will understand how to instantiate the XML DOMDocument control, load an XML document, and get data from the tree. These are the basics upon which all other XML document processing is built.

Though the document above took more work to create than the simple HTML equivalent, some useful benefits can be realized by using XML. The biggest is that a Web page can become a template for data. The HTML page created above can be used as a template for any XML content that fits that predefined model. Although creating the HTML page took some work, it can be used over and over with different content. For example, the XML document could be translated into another language, such as French or German, and still be plugged into the same HTML template.

There are other ways to get XML data into a Web page than just the DOMDocument object, such as the XML Data Source Object, XSL, and XSL Patterns. These techniques add more benefits to the use of XML for structuring and storing data. You can find out more about these on the SBN Workshop Web site and on the CD that accompanies this book. On the CD see XML (Extensible Markup Language), and choose any topic from the XML TOC (XML Table of Contents). To get to the online version, visit the MSDN Online Resource page at msdn.microsoft.com/resources/schurmandhtml.htm, or open the file named MSDN_OL.htm on the companion CD, and choose XML (Extensible Markup Language). The following tables describe aspects of the XML Document Object Model.

Table 21-1 XML Document Properties

PropertyDescription
asyncReturns a Boolean value specifying whether asynchronous download is allowed. Value is true if asynchronous download is permitted, false if not. Read/Write.
attributesReturns an object containing a list of attributes for the current node. If the node cannot contain attributes, null is returned. Read-only.
childNodesReturns an object containing a node list of all the available children of the current node. If the node does not contain children, null is returned. Read-only.
doctypeReturns an object containing the document type node holding the DTD for the current document. If the document does not contain a DTD, null is returned. Read-only.
documentElementReturns an object that contains the data in the root Document element. If the document does not contain a root, null is returned. Read/Write.
firstChild Returns an object containing the first child element of the current node. If the node does not contain a first child element, null is returned. Read-only.
implementation Returns the Document Object Model (DOM) implementation object for the current XML document. Read-only.
lastChild Returns an object containing the last child element of the current node. If the node does not contain a last child element, null is returned. Read-only.
nextSibling Returns an object containing the next sibling in the child list of the current document node. If the node does not contain a next sibling node, null is returned. Read-only.
nodeNameReturns a string representing the qualified name of the current node (element, attribute, or entity reference). Read-only.
nodeTypeReturns a number representing the DOM type (element, attribute, text) of the current node. Read-only.
nodeValue Returns the text associated with a specified node. This is not the value of the data in an element, but rather unparsed text that might be associated with a node, such as an attribute or a processing instruction. Returns null for nodes of certain types. Read/Write.
ondataavailable Specifies an event handler for the ondataavailable event. Write-only.
onreadystatechange Specifies an event handler for the onreadystatechange event. Write-only.
ownerDocument Returns an object containing the root node for the document containing the current node. Read-only.
parentNode Returns an object containing the parent node of the current node. If the node does not exist in the tree, null is returned. Read-only.
parseError Returns a DOM parse error object that describes the last parse error. If no error has occurred, 0 is returned. Read-only.
previousSibling Returns an object containing the sibling node that occurs just before the current node. If the node does not contain a previous sibling node, null is returned. Read-only.
readyState Returns a number representing the current state of the XML document data. Read-only. Values are as follows: 0 (uninitialized) XML object is created but no document is loaded.
1 (loading) Load in progress, but parsing has not yet started.
2 (loaded) Some of the document is loaded and parsing has begun, but the object model is not available.
3 (interactive) Object model is available for loaded portions of the document.
4 (completed) Document completely loaded. This does not necessarily mean the load was successful.
url Returns the URL for the last document that was loaded successfully. If the document exists only in memory (it was not loaded from an external file), null is returned. Read-only.
validateOnParse Indicates to the parser whether the document should be validated. If true, the document is validated when it is parsed. If false, the document is not validated and is expected only to be well-formed. Read/Write.
xml Returns the XML representation of the specified node and any descendants. Read-only.

Table 21-2 XML Document Methods

MethodDescription
abort() If this method is called during an asynchronous download, all parsing is stopped and any portion of the document in memory is discarded.
appendChild(newChild) Appends a node as the last child of the specified node.
cloneNode(deep) Creates an exact replica of a specified node. The deep parameter is a Boolean value. If true, the node is cloned with all of its descendants. If false, only the specified node and its attributes are cloned.
createAttribute(name) Creates an attribute with a specified name.
createCDATASection(data) Creates a CDATA section that contains the specified string data.
createComment(data) Creates a comment that contains the specified string data.
createDocumentFragment() Creates a new document fragment but does not add it to the document tree. To add it to the tree, an insert method must be used, such as insertBefore, replaceChild, or appendChild.
createElement(tagname) Creates an element with the specified (case-sensitive) tag name.
createEntityReference(name) Creates a new entity reference with the specified name, but does not add it to the document tree. To add it to the tree, an insert method must be used, such as insertBefore, replaceChild, or appendChild.
createNode(type, name, nameSpaceURL) Creates a new node with the specified type, name, and namespace.
createProcessingInstruction(target, data) Creates a new processing instruction containing the specified target and data, but does not add it to the tree. To add it to the tree, an insert method must be used, such as insertBefore, replaceChild, or appendChild.
createTextNode(data) Creates a new text node containing the specified data, but does not add it to the tree. To add it to the tree, an insert method must be used, such as insertBefore, replaceChild, or appendChild.
getElementsByTagName(tagname) Returns a collection of elements with the specified name. Using the tagname "*" returns all the elements found in the document.
hasChildNodes() Returns true if the node has children, false otherwise.
insertBefore(newChild, refChild) Inserts a new child node before a reference node. The newChild parameter is an object containing the address of the new child node, while refChild is the address of the reference node. If the refChild parameter is not included, the new child is inserted at the end of the child list.
load(url) Loads the indicated document from the specified location. Returns true if the document loads successfully, false otherwise.
loadXML(xmlString) Loads an XML document or fragment from a string. Returns true if the document loads successfully, false otherwise.
nodeFromID(idString) Returns a node for which the node ID matches the specified value. If a match is found, an object is returned. If the operation fails, null is returned.
parsed() If the current node and all its descendants have been parsed and instantiated, true is returned. If any part of the node has not yet been parsed, false is returned.
removeChild(child) Removes the specified child node from the node list. The child parameter is an object containing the child node to be removed.
replaceChild(newChild, oldChild) Replaces the specified old child node with the supplied new child node. If newChild is null, the old child is removed without a replacement.
selectNodes(patternString) Returns a node list object containing nodes that match the supplied XSL pattern.
selectSingleNode(patternString) Returns the first node that matches the supplied XSL pattern. If no matches are found, null is returned.
transformNode(stylesheet) Returns a string containing the result of processing the current node and its child nodes using the supplied XSL style sheet.

Table 21-3 XML Document Events

EventDescription
ondataavailable The ondataavailable event is fired as soon as any data is available. This technique does not indicate how much of a given document is available.
onreadystatechange The onreadystatechange event is fired when the readyState property changes, but the event does not indicate what the ready state is. Use the readyState property to get the current state.



Dynamic HTML in Action
Dynamic HTML in Action
ISBN: 0735605637
EAN: 2147483647
Year: 1999
Pages: 128

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net