The Primary XML DOM Classes

The most significant XML DOM classes the Document class, the Element class, the Attr (or Attribute) class, and the Text class are shown in Figure 2-3.

image from book
Figure 2-3: The most significant XML DOM classes

The classes shown in Figure 2-3 generally perform the following functions:

  • Node class and NodeList class: The Node class is an abstract of many other classes in the XML DOM, including the Document , Element , Attr , and Text classes. The NodeList class contains a collection of Node class objects within each node object instantiation of the Node class.

  • Document class: Contains the entire XML document including all elements (tags) and text. Elements are metadata and text is data. So, the Document class contains all structural metadata and data.

    It is important to remember that the XML DOM provides direct programmatic (or dynamic) access to both metadata and data.

  • Element class: Every tag in an XML document is represented by an iteration of (a copy of or an object of) the Element class. Within every element are zero or more child elements.

  • Attr class: Every element can have attributes helping to refine the behavior of specific Element class objects.

  • Text class: The data (not the metadata) is contained within Text class iteration objects.

All details in figures in this chapter are deliberately sparse because the names of attributes and nodes are assumed to be intuitive. In others words, a methods name describes exactly what its function is. Anything not detailed is self-explanatory. It is what it is, nothing more, nothing less. Also, less cluttered diagrams are so much easier to read.

The Node Class

The Node class is essentially an abstraction of all inherited classes. The Node class contains abstracted definitions of classes inherited from it. The Document class is a good example of a class inheriting attributes and methods from the Node class. However, all the primary XML DOM classes inherit attributes and methods from the Node class. Thus the Node class is an abstraction of the Document , Element , Attr , and Text classes.

An abstracted class is a little like a generalized class as it takes all the attributes and methods common to its child classes, and removes them to itself as a single abstracted class. The child classes then inherit those attributes and methods from the abstracted parent class. In this case, the parent class is the Node class, which is of course the abstracted class. Use of the word abstract defines the Node class as a summary or abstract of all the important points about other classes in the XML DOM. Essentially, its the same thing as the abstract of a document such as a scientific paper summarizing all the key points of that paper.

Because the Node class is an abstraction, it contains attributes and methods that can be used by all inherited classes, as shown in Figure 2-4.

image from book
Figure 2-4: The XML DOM Node class attributes and methods that are inherited by child classes within the XML DOM

In Figure 2-4 inheritance implies, for example, that the attributes collection can be accessed at the Node class level, as shown in the following example:

   Node.attributes   

And at the inherited level for the Document class, as in:

   Document.attributes   

And similarly as applied to the Element class, as in:

   Element.attributes   

The same does not apply to the Attr class because each instantiation of the Attr class creates a single attribute object. A single attribute is not a collection of attributes. In other words, attributes do not have attribute collections of their own.

The same applies to both attributes and methods. So, for the Node class method appendChild(newnode) the same applies as shown here:

   Node.appendChild("newChildNode")   

And for the Document class:

   Document.appendChild("newChildNode")   

And the Element class:

   Element.appendChild("newChildNode")   

The NodeList Class

The NodeList class is a little like an array or collection contained within the Node class. The NodeList class can be very useful for iterating through objects contained within the Node class structure.

Iterating through an array implies scrolling through an array one by one, programmatically. This gives complete access to all child objects contained within each node of an XML document.

The NodeList class can be used to retrieve an entire XML document, or a subset thereof, including the nodes and all child nodes contained within that node. Figure 2-5 shows the attributes and methods for the NodeList class.

image from book
Figure 2-5: The XML DOM NodeList class is an array or collection of nodes within an XML document.

The NodeList class could be accessed as a part of the childNodes Node class collection as follows :

   xmlDoc.documentElement.childNodes.item(0)   

The preceding example uses the Node class childNodes collection, and finds all the text values within the first element of the root node of an XML document.

The NamedNodeMap Class

Unlike the NodeList class, which is an ordered collection, the NamedNodeMap class is an unordered collection. All this means is that it has to access as an iteration through an array. The only attribute of a NamedNodeMap class is length, determining the number of items in the collection. The Node class attributes property is a NamedNodeMap class object.

Try It OutUsing the Node Class
image from book

This is an XML document representing all states in the United States and some of the provinces in Canada. The data in this XML document is intentionally unsorted. Assume that this file is called countries .xml:

   <?xml version="1.0" ?> <countries>    <country name="Canada">       <state name="Alberta">AB</state>       <state name="Nova Scotia">NS</state>       <state name="British Columbia">BC</state>       <state name="Quebec">QB</state>       <state name="Ontario">ON</state>    </country>    <country name="United States">       <state name="Colorado">CO</state>       <state name="Connecticut">CT</state>       <state name="Delaware">DE</state>       <state name="Florida">FL</state>       <state name="Georgia">GA</state>       <state name="Hawaii">HI</state>       <state name="Iowa">IA</state>       <state name="Idaho">ID</state>       <state name="Illinois">IL</state>       <state name="Indiana">IN</state>       <state name="Kansas">KS</state>       <state name="Kentucky">KY</state>       <state name="Louisiana">LA</state>       <state name="Massachusetts">MA</state>       <state name="Maryland">MD</state>       <state name="Maine">ME</state>       <state name="Minnesota">MN</state>       <state name="Missouri">MO</state>       <state name="Mississippi">MS</state>       <state name="Montana">MT</state>       <state name="North Carolina">NC</state>       <state name="North Dakota">ND</state>       <state name="New Hampshire">NH</state>       <state name="New Jersey">NJ</state>       <state name="Nebraska">NE</state>       <state name="New Mexico">NM</state>       <state name="Nevada">NV</state>       <state name="New York">NY</state>       <state name="Ohio">OH</state>       <state name="Oklahoma">OK</state>       <state name="Oregon">OR</state>       <state name="Pennsylvania">PA</state>       <state name="Rhode Island">RI</state>       <state name="South Carolina">SC</state>       <state name="South Dakota">SD</state>       <state name="Tennessee">TN</state>       <state name="Texas">TX</state>       <state name="Utah">UT</state>       <state name="Vermont">VEM</state>       <state name="Virginia">VA</state>       <state name="Washington">WA</state>       <state name="Wisconsin">WI</state>       <state name="West Virginia">WV</state>       <state name="Wyoming">WY</state>       <state name="California">CA</state>       <state name="Arizona">AZ</state>       <state name="Arkansas">AR</state>       <state name="Alabama">AL</state>       <state name="Alaska">AK</state>       <state name="Michigan">MI</state>    </country> </countries>   

Find the type, name, and value of the node for the second to last state in the XML document. Do not use the Node class nodeValue attribute. The type, name, and value of a node can be found using the Node class nodeType , nodeName , and text attributes.

Follow these steps to create an HTML file that includes a JavaScript <SCRIPT> tag section and that includes the appropriate XML DOM scripting commands in order to retrieve the required values:

  1. Create an HTML file as follows:

       <HTML><BODY> <SCRIPT LANGUAGE="JavaScript"> </SCRIPT> </BODY></HTML>   
  2. Create the XML document object in the XML DOM and load the XML document into the variable:

       <HTML><BODY> <SCRIPT LANGUAGE="JavaScript"> var xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.load("countries.xml"); </SCRIPT> </BODY></HTML>   
  1. Add a variable to find the targeted element, the second to last state in the XML document, which happens to be in the second country, the United States, and is the state of Alaska:

       <HTML><BODY> <SCRIPT LANGUAGE="JavaScript"> var xmlDoc; xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.load("countries.xml"); var root = xmlDoc.documentElement.lastChild.lastChild.previousSibling; </SCRIPT> </BODY></HTML>   

    In the preceding code, the variable called root is set to the lastChild (the last element in the root node), which is the last country (the United States). The lastChild.lastChild is the last state in the United States. previousSibling finds the second to last state in the United States (the second to last state in the XML document).

  2. Last but not least, return the node type, node name, and value using the Node class nodeType , nodeName , and text attributes:

       <HTML><BODY> <SCRIPT LANGUAGE="JavaScript"> var xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.load("countries.xml"); var root = xmlDoc.documentElement.lastChild.lastChild.previousSibling; document.write("nodeType  :" + root.nodeType + "<BR>"); document.write("nodeName  :" + root.nodeName + "<BR>"); document.write("text :" + root.text + "<BR>"); </SCRIPT> </BODY></HTML>   

The final result looks as shown in Figure 2-6.

image from book
Figure 2-6: Working with the XML DOM Node class

How It Works

You created an HTML file that included a JavaScript section. You then created an XML document variable object, loading an XML document into that document object variable. Next you created a variable and set it to the previous sibling of the last child, of the last child. In other words, you parsed (scanned through) the XML document and found the last child element in the root node, which is the United States. Within the last element you found its last node and you found Michigan. Then you found the node previous to Michigan, which is Alaska. Once again, the elements in this document are not sorted in any particular order this is intentional. Later on in this book you learn ways to sort data that do not include manually rearranging an XML document in a text editor. It is much easier to let a computer do things such as sorting for you. In the last step you used various attributes of the node you had found (Alaska) to dump information onto the browser display. This demonstrates programmatic access to an XML document, regardless of its specific data content, or even whether or not it is sorted.

image from book
 

There is a possibility that some of the scripts here may not run on your computer, depending on your operating system, the browser you are using, the version of the browser you are using, and even some of the security settings in your browser. I do not suggest changing any security settings, or anything else on your computer, just to get examples running. Most examples are displayed in working order in figures anyway.

The Document Class

The Document class attributes and methods are shown in Figure 2-7. The grayed out sections show all the attributes and methods that are inherited from the Node class. Inherited attributes and methods can be executed against a node object (instantiation of a Node class) or against a document object (instantiation of the Document class) because they are inherited. Inheritance means that a document object automatically has access to all the goodies in the Node class, plus anything overriding the Node class by the Document class. By definition this also makes the Node class an abstracted class of the Document class. That is what inheritance is.

image from book
Figure 2-7: The XML DOM Document class

Again, most attributes and methods are self-explanatory.

Important 

Grayed out attributes and methods are inherited from a parent class but are still applicable to, and usable on, document objects instantiated from this class.

The following is an XML document representing a group of customers:

   <?xml version="1.0" ?> <customers>    <customer>       <name phone="631-445-2231">Zachary Smith</name>       <address>          <street>1 Smith Street</street>          <town>Smithtown</town>          <state>NY</state>          <zip>11723</zip>       </address>    </customer>    <customer>       <name phone="516-456-5467">Jim Jones</name>       <address>          <street>25 Amery Street</street>          <town>Jones Beach</town>          <state>NY</state>          <zip>11744</zip>       </address>    </customer>    <customer>       <name phone="631-123-4567">Joe Bloggs</name>       <address>          <street>PO Box 4261</street>          <town>New York</town>          <state>NY</state>          <zip>22451</zip>       </address>    </customer>    <customer>       <name phone="212-123-5566">James Bloggs</name>       <address>          <street>25 5th Street</street>          <town>Manhattan</town>          <state>NY</state>          <zip>11124</zip>       </address>    </customer> </customers>   

Figure 2-8 shows the same group of customers as before, but from within a browser.

image from book
Figure 2-8: Viewing an XML document in a browser shows a clear picture of hierarchical structure

Now lets build an HTML page using JavaScript in order to access parts of the XML document. Start by creating the initial tags for an HTML page:

   <HTML> <HEAD><TITLE>The XML DOM in JavaScript</TITLE></HEAD> <BODY> </BODY></HTML>   

Next, create the JavaScript tag and open the XML document as an ActiveX object and using the Document class load method:

   <HTML> <HEAD><TITLE>The XML DOM in JavaScript</TITLE></HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> var xmlDoc; xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.load("customers.xml"); </SCRIPT> </BODY></HTML>   

Finally, put the Document class object into a variable using the documentElement attribute, the Node class childNodes attribute (inherited), and the NodeList class item collection (inherited). This example finds the first element within the root node and displays it:

   <HTML> <HEAD><TITLE>The XML DOM in JavaScript</TITLE></HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> var xmlDoc; xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.load("customers.xml"); var root = xmlDoc.documentElement.childNodes.item(0); document.write(root.xml); </SCRIPT> </BODY></HTML>   

Figure 2-9 shows the result of running the preceding HTML code.

image from book
Figure 2-9: Using JavaScript and the XML DOM to view an XML document

The Document class also has something specific to Document class instantiated objects called events . An event is a function or process that executes when the specified events occur to an XML document. These functions can have custom code in them (programmed specifically by a programmer for each XML document):

  • Document.OnDataAvailable="GoDoThis" : Executes when an XML document becomes available.

  • Document.OnReadyStateChange="GoDoThis" : Executes when an XML document ReadyState attribute changes.

  • Boolean = OnTransformNodeBoolean : Executes before a node is transformed by an XSL transformation.

Demonstrating Document class events is beyond the scope of this book.

The Element Class

The Element class comprises the definitional structure for all the elements or tags created and placed into an XML document. Figure 2-10 shows all the interesting attributes and methods for the Element class. Once again, all is self-explanatory and including examples at this stage would probably just be excess.

image from book
Figure 2-10: The XML DOM Element class contains all the tags in an XML document.
Important 

Grayed out attributes and methods are inherited from a parent class but are still applicable to, and usable on, document objects instantiated from this class.

Using the previous example again, we can use the Element class tagName attribute to return the names of elements:

   <HTML> <HEAD><TITLE>The XML DOM in JavaScript</TITLE></HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> //Create the object: var xmlDoc; xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.load("customers.xml"); //Put the object into a variable var root = xmlDoc.documentElement.childNodes.item(0); document.writeln("Root : " + root.tagName + "<BR>"); for (i = 0; i < root.childNodes.length; i++) {    document.writeln("&nbsp;&nbsp;&nbsp;Parent " + i + ": "       + root.childNodes.item(i).tagName + "<BR>");    child = root.childNodes.item(i);    for (j = 0; j < child.childNodes.length; j++)    {       document.writeln("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Child " + j + ": "          + child.childNodes.item(j).tagName + "<BR>");    } } </SCRIPT> </BODY></HTML>   

The result of the preceding script is shown in Figure 2-11.

image from book
Figure 2-11: Using JavaScript and the XML DOM to view XML document elements

The Attr Class

The Attr (Attribute) class is nice and easy, having only three attributes (one is irrelevant to this text) and no methods. The two relevant attributes are shown in Figure 2-12.

image from book
Figure 2-12: The XML DOM Attr (attribute) class has no inherited attributes or methods.

It is important to understand that XML document Attr class objects are name-value pairs attached to an element:

 <address  phone="631-445-2231"  > 

Attr class objects are not part of the XML document hierarchical structure itself. In other words, Attr class objects do not define metadata structures within an XML document because they are not tags (elements). Elements make up structure. Attr class objects refine only properties of elements, which is the semantics of the word attributes in this context. The result is that the Attr class does not inherit attributes and methods from the other classes.

The Attr class does not inherit attributes and methods from other classes in the XML DOM, such as Node , Document , and Element classes.

Attr class attributes can be utilized as follows:

  • Attr.Name : The name of an attribute as in the boldface section here:

       <country  name  ="Germany">   
  • Attr.Value : Allows recovery of or setting of the value of an attribute:

       <country name="  Germany  ">   

Using the previous example again, you can use the Attr (attribute) class name and value attributes to return the names and telephone numbers :

   <HTML> <HEAD><TITLE>The XML DOM in JavaScript</TITLE></HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> //Create the object: var xmlDoc; xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.load("customers.xml"); var names = xmlDoc.getElementsByTagName("name"); for (i = 0; i < names.length; i++) {    document.write(names.item(i).attributes(0).name + " "       + names.item(i).attributes(0).value + "<BR><BR>"); } </SCRIPT> </BODY></HTML>   

The result of the preceding script is shown in Figure 2-13.

image from book
Figure 2-13: Using JavaScript and the XML DOM to view an XML documents element attributes

The Text Class

The Text class gives structure and access to the data (textual parts) within an XML document. Figure 2-14 shows all the interesting attributes and methods for the Text class.

image from book
Figure 2-14: The XML DOM Text class contains values between tag elements.
Important 

Grayed out attributes and methods are inherited from a parent class but are still applicable to, and usable on, document objects instantiated from this class.

And yet again, using the previous example I have added another line to the JavaScript for loop to display the Text class object for the customer <name> element:

   <HTML> <HEAD><TITLE>The XML DOM in JavaScript</TITLE></HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> //Create the object: var xmlDoc; xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.load("customers.xml"); var names = xmlDoc.getElementsByTagName("name"); for (i = 0; i < names.length; i++) {    document.write(names.item(i).text + ": "       + names.item(i).attributes(0).name + " "       + names.item(i).attributes(0).value + "<BR><BR>"); } </SCRIPT> </BODY></HTML>   

The result of the preceding script is shown in Figure 2-15.

image from book
Figure 2-15: Using JavaScript and the XML DOM to view an XML documents element text values


Beginning XML Databases
Beginning XML Databases (Wrox Beginning Guides)
ISBN: 0471791202
EAN: 2147483647
Year: 2006
Pages: 183
Authors: Gavin Powell

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