Chapter: Internet & World Wide Web HOW TO PROGRAM - The Ajax Client - XML and RSS

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Document Object Model (DOM)

Although an XML document is a text file, retrieving data from the document using tradi-tional sequential file processing techniques is neither practical nor efficient, especially for adding and removing elements dynamically.

Document Object Model (DOM)

 

Although an XML document is a text file, retrieving data from the document using tradi-tional sequential file processing techniques is neither practical nor efficient, especially for adding and removing elements dynamically.

 

Upon successfully parsing a document, some XML parsers store document data as tree structures in memory. Figure 14.25 illustrates the tree structure for the root element of the document article.xml (Fig. 14.2). This hierarchical tree structure is called a Document Object Model (DOM) tree, and an XML parser that creates this type of structure is known as a DOM parser. Each element name (e.g., article, date, firstName) is repre-sented by a node. A node that contains other nodes (called child nodes or children) is called a parent node (e.g., author). A parent node can have many children, but a child node can have only one parent node. Nodes that are peers (e.g., firstName and lastName) are called sibling nodes. A node’s descendant nodes include its children, its children’s chil-dren and so on. A node’s ancestor nodes include its parent, its parent’s parent and so on. Many of the XML DOM capabilities you’ll see in this section are similar or identical to those of the XHTML DOM you learned in Chapter 12.

 

The DOM tree has a single root node, which contains all the other nodes in the doc-ument. For example, the root node of the DOM tree that represents article.xml con-tains a node for the XML declaration (line 1), two nodes for the comments (lines 3–4) and a node for the XML document’s root element article (line 5).


To introduce document manipulation with the XML Document Object Model, we provide a scripting example (Fig. 14.26) that uses JavaScript and XML. This example loads the XML document article.xml (Fig. 14.2) and uses the XML DOM API to dis-play the document’s element names and values. The example also provides buttons that enable you to navigate the DOM structure. As you click each button, an appropriate part of the document is highlighted. All of this is done in a manner that enables the example to execute in both Internet Explorer 7 and Firefox 2. Figure 14.26 lists the JavaScript code that manipulates this XML document and displays its content in an XHTML page.

 

Overview of the body Element

Lines 203–217 create the XHTML document’s body. When the body loads, its onload event calls our JavaScript function loadXMLDocument to load and display the contents of article.xml in the div at line 216 (outputDiv). Lines 204–215 define a form consisting of five buttons. When each button is pressed, it invokes one of our JavaScript functions to navigate article.xml’s DOM structure.

 

Global Script Variables

Lines 16–21 in the script element (lines 14–201) declare several variables used through-out the script. Variable doc references a DOM object representation of article.xml. Variable outputHTML stores the markup that will be placed in outputDiv. Variable id-Counter is used to track the unique id attributes that we assign to each element in the out-putHTML markup. These ids will be used to dynamically highlight parts of the document when the user clicks the buttons in the form. Variable depth determines the indentation level for the content in article.xml. We use this to structure the output using the nesting of the elements in article.xml. Variables current and previous track the current and previous nodes in article.xml’s DOM structure as the user navigates it.

 

 

 

1    <?xml version = "1.0" encoding = "utf-8"?>

 

2    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

3          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4              

5    <!-- Fig. 14.26: XMLDOMTraversal.html -->

 

6    <!-- Traversing an XML document using the XML DOM. -->

 

7    <html xmlns = "http://www.w3.org/1999/xhtml">

 

8    <head>

 

9          <title>Traversing an XML document using the XML DOM</title>

 

10         <style type = "text/css">

 

11               .highlighted { background-color: yellow }

 

12               #outputDiv { font: 10pt "Lucida Console", monospace; }

 

13         </style>

 

14         <script type="text/javascript">

15         <!--

 

16         var doc; // variable to reference the XML document

 

17         var outputHTML = ""; // stores text to output in outputDiv

 

18         var idCounter = 1; // used to create div IDs

 

19         var depth = -1; // tree depth is -1 to start

 

20         var current = null; // represents the current node for traversals

 

21         var previous = null; // represent prior node in traversals

22

23         // load XML document based on whether the browser is IE7 or Firefox 2

 

24         function loadXMLDocument( url )

25         {

 

26               if ( window.ActiveXObject ) // IE7

27               {

 

28                      // create IE7-specific XML document object

 

29                      doc = new ActiveXObject( "Msxml2.DOMDocument.6.0" );

 

30                      doc.async = false; // specifies synchronous loading of XML doc

 

31                      doc.load( url ); // load the XML document specified by url

 

32                      buildHTML( doc.childNodes ); // display the nodes

 

33                      displayDoc();

 

34               } // end if

 

35               else if ( document.implementation &&

 

36                      document.implementation.createDocument ) // other browsers

37               {

 

38                      // create XML document object

 

39                      doc = document.implementation.createDocument( "", "", null );

 

40                      doc.load( url ); // load the XML document specified by url

 

41                      doc.onload = function() // function to execute when doc loads

42                      {

43                      buildHTML( doc.childNodes ); // called by XML doc onload event

44                      displayDoc(); // display the HTML

 

44                      } // end XML document's onload event handler

 

45               } // end else

 

46               else // not supported

 

47                      alert( 'This script is not supported by your browser' );

 

48         } // end function loadXMLDocument

50

51         // traverse xmlDocument and build XHTML representation of its content

 

52         function buildHTML( childList )

53         {


 

++depth; // increase tab depth

 

55

56                // display each node's content

 

57                for ( var i = 0; i < childList.length; i++ )

58                {

 

59                      switch ( childList[ i ].nodeType )

{

61        case 1: // Node.ELEMENT_NODE; value used for portability

62        outputHTML += "<div id=\"id" + idCounter + "\">";

63        spaceOutput( depth ); // insert spaces     

64        outputHTML +=        childList[ i ].nodeName;      // show node's name

65        ++idCounter; // increment the id counter

66                                                                                                       

67        // if current node has children, call buildHTML recursively

68        if (        childList[ i ].childNodes.length      != 0 )

69                    buildHTML( childList[ i ].childNodes );                

70                                                                                                       

71        outputHTML += "</div>";    

72        break;

73        case 3: // Node.TEXT_NODE; value used for portability

74        case 8: // Node.COMMENT_NODE; value used for portability

75        // if nodeValue is not 3 or 6 spaces (Firefox issue),

76        // include nodeValue in HTML     

77        if ( childList[ i ].nodeValue.indexOf( "       " ) == -1 &&

78        childList[ i ].nodeValue.indexOf( "            " ) == -1 )

79        {                                                                                              

80        outputHTML += "<div id=\"id" + idCounter + "\">";

81        spaceOutput( depth ); // insert spaces     

82        outputHTML +=        childList[ i ].nodeValue       + "</div>";

83        ++idCounter; // increment the id counter

84        } // end if        

85                      } // end switch

 

86                } // end for

87

88                --depth; // decrease tab depth

 

89         } // end function buildHTML

90

91         // display the XML document and highlight the first child

 

92         function displayDoc()

93         {

 

94                document.getElementById( "outputDiv" ).innerHTML = outputHTML;

 

95                current = document.getElementById( 'id1' );

 

96                setCurrentNodeStyle( current.id, true );

 

97         } // end function displayDoc

98

99   // insert non-breaking spaces for indentation

 

100      function spaceOutput( number )

101      {

 

102             for ( var i = 0; i < number; i++ )

103             {

 

104                   outputHTML += "&nbsp;&nbsp;&nbsp;";

105             } // end for

 

106      } // end function spaceOutput


 

107

108     // highlight first child of current node

 

109     function processFirstChild()

110     {

 

111            if ( current.childNodes.length == 1 && // only one child

 

112                   current.firstChild.nodeType == 3// and it's a text node

113            {

 

114                   alert( "There is no child node" );

115            } // end if

 

116            else if ( current.childNodes.length > 1 )

117            {

 

118                   previous = current; // save currently highlighted node

119

120                   if ( current.firstChild.nodeType != 3 ) // if not text node

 

121                         current = current.firstChild; // get new current node

 

122                   else // if text node, use firstChild's nextSibling instead

 

123                           current = current.firstChild.nextSibling; // get first sibling

124      

125                   setCurrentNodeStyle( previous.id, false ); // remove highlight

 

126                   setCurrentNodeStyle( current.id, true ); // add highlight

127            } // end if

128            else

 

129                   alert( "There is no child node" );

 

130     } // end function processFirstChild

131

132     // highlight next sibling of current node

 

133     function processNextSibling()

134     {

 

135            if ( current.id != "outputDiv" && current.nextSibling )

136            {

 

137                   previous = current; // save currently highlighted node

 

138                   current = current.nextSibling; // get new current node

 

139                   setCurrentNodeStyle( previous.id, false ); // remove highlight

 

140                   setCurrentNodeStyle( current.id, true ); // add highlight

141            } // end if

142            else

 

143                   alert( "There is no next sibling" );

 

144     } // end function processNextSibling

145

146     // highlight previous sibling of current node if it is not a text node

 

147     function processPreviousSibling()

148     {

 

149            if ( current.id != "outputDiv" && current.previousSibling &&

 

150                   current.previousSibling.nodeType != 3 )

151            {

 

152                   previous = current; // save currently highlighted node

 

153                   current = current.previousSibling; // get new current node

 

154                   setCurrentNodeStyle( previous.id, false ); // remove highlight

 

155                   setCurrentNodeStyle( current.id, true ); // add highlight

156            } // end if

157            else

 

158                   alert( "There is no previous sibling" );

 

159     } // end function processPreviousSibling


 

160

161     // highlight last child of current node

 

162     function processLastChild()

163     {

 

164            if ( current.childNodes.length == 1 &&

 

165                   current.lastChild.nodeType == 3 )

166            {

 

167                   alert( "There is no child node" );

168            } // end if

 

169            else if ( current.childNodes.length != 0 )

170            {

 

171                   previous = current; // save currently highlighted node

 

172                   current = current.lastChild; // get new current node

 

173                   setCurrentNodeStyle( previous.id, false ); // remove highlight

 

174                   setCurrentNodeStyle( current.id, true ); // add highlight

175            } // end if

176            else

 

177                   alert( "There is no child node" );

 

178     } // end function processLastChild

179

180     // highlight parent of current node

 

181     function processParentNode()

182     {

 

183            if ( current.parentNode.id != "body" )

184            {

 

185                   previous = current; // save currently highlighted node

 

186                   current = current.parentNode; // get new current node

 

187                   setCurrentNodeStyle( previous.id, false ); // remove highlight

 

188                   setCurrentNodeStyle( current.id, true ); // add highlight

189            } // end if

190            else

 

191                   alert( "There is no parent node" );

 

192     } // end function processParentNode

193

194     // set style of node with specified id

 

195     function setCurrentNodeStyle( id, highlight )

196     {

 

197            document.getElementById( id ).className =

 

198                   ( highlight ? "highlighted" : "" );

 

199     } // end function setCurrentNodeStyle

200     // -->

 

201     </script>

 

202     </head>

 

203     <body id = "body" onload = "loadXMLDocument( 'article.xml' );">

 

204     <form action = "" onsubmit = "return false;">

 

205            <input type = "submit" value = "firstChild"

 

206                   onclick = "processFirstChild()"/>

 

207            <input type = "submit" value = "nextSibling"

 

208                   onclick = "processNextSibling()"/>

 

209            <input type = "submit" value = "previousSibling"

 

210                   onclick = "processPreviousSibling()"/>

 

211            <input type = "submit" value = "lastChild"

 

212                   onclick = "processLastChild()"/>


 

 

213            <input type = "submit" value = "parentNode"

 

214                   onclick = "processParentNode()"/>

 

215     </form><br/>

 

216     <div id = "outputDiv"></div>

 

217     </body>

 

218     </html>

 











Fig. 14.26 | Traversing an XML document using the XML DOM.

 

Function loadXMLDocument

Function loadXMLDocument (lines 24–49) receives the URL of an XML document to load, then loads the document based on whether the browser is Internet Explorer 7 (26–34) or Firefox 2 (lines 35–46)—the code for Firefox 2 works in several other browsers as well. Line 26 determines whether window.ActiveXObject exists. If so, this indicates that the browser is Internet Explorer. Line 29 creates a Microsoft ActiveXObject that loads Mi-crosoft’s MSXML parser, which provides capabilities for manipulating XML documents. Line 30 indicates that we’d like the XML document to be loaded synchronously, then line

 

31 uses the ActiveXObject’s load method to load article.xml. When this completes, we call our buildHTML method (defined in lines 52–89) to construct an XHTML representa-tion of the XML document. The expression doc.childNodes is a list of the XML docu-ment’s top-level nodes. Line 33 calls our displayDoc function (lines 92–97) to display the contents of article.xml in outputDiv.

 

If the browser is Firefox 2, then the document object’s implementation property and the implementation property’s createDocument method will exist (lines 35–36). In this case, line 39 uses the createDocument method to create an empty XML document object. If necessary, you can specify the XML document’s namespace as the first argument and its root element as the second argument. We used empty strings for both in this example.

 

According to the site  www.w3schools.com/xml/xml_parser.asp, the third argument is not implemented yet, so it should always be null. Line 40 calls its load method to load article.xml. Firefox loads the XML document asynchronously, so you must use the XML document’s onload property to specify a function to call (an anonymous function in this example) when the document finishes loading. When this event occurs, lines 43– 44 call buildHTML and displayDoc just as we did in lines 32–33.

Function buildHTML

 

Function buildHTML (lines 52–89) is a recursive function that receives a list of nodes as an argument. Line 54 increments the depth for indentation purposes. Lines 57–86 iterate through the nodes in the list. The switch statement (lines 59–85) uses the current node’s nodeType property to determine whether the current node is an element (line 61), a text node (i.e., the text content of an element; line 73) or a comment node (line 74). If it is an element, then we begin a new div element in our XHTML (line 62) and give it a unique id. Then function spaceOutput (defined in lines 100–106) appends nonbreaking spaces (&nbsp;)—i.e., spaces that the browser is not allowed to collapse or that can be used to keep words together—to indent the current element to the correct level. Line 64 appends the name of the current element using the node’s nodeName property. If the current ele-ment has children, the length of the current node’s childNodes list is nonzero and line 69 recursively calls buildHTML to append the current element’s child nodes to the markup. When that recursive call completes, line 71 completes the div element that we started at line 62.

 

If the current element is a text node, lines 77–78 obtain the node’s value with the nodeValue property and use the string method indexOf to determine whether the node’s value starts with three or six spaces. Unfortunately, unlike MSMXL, Firefox’s XML parser does not ignore the white space used for indentation in XML documents. Instead it creates text nodes containing just the space characters. The condition in lines 77–78 enables us to ignore these nodes in Firefox. If the node contains text, lines 80–82 append a new div to the markup and use the node’s nodeValue property to insert that text in the div. Line 88 in buildHTML decrements the depth counter.

Function displayDoc

In function displayDoc (lines 92–97), line 94 uses the DOM’s getElementById method to obtain the outputDiv element and set its innerHTML property to the new markup gen-erated by buildHTML. Then, line 95 sets variable current to refer to the div with id 'id1' in the new markup, and line 96 uses our setCurrentNodeStyle method (defined at lines 195–199) to highlight that div.

 

Functions processFirstChild and processLastChild

Function processFirstChild (lines 109–130) is invoked by the onclick event of the but-ton at lines 205–206. If the current node has only one child and it’s a text node (lines 111–112), line 114 displays an alert dialog indicating that there is no child node—we nav-igate only to nested XML elements in this example. If there are two or more children, line 118 stores the value of current in previous, and lines 120–123 set current to refer to its firstChild (if this child is not a text node) or its firstChild’s nextSibling (if the firstChild is a text node)—again, this is to ensure that we navigate only to nodes that represent XML elements. Then lines 125–126 unhighlight the previous node and high-light the new current node. Function processLastChild (lines 162–178) works similar-ly, using the current node’s lastChild property.

Functions processNextSibling and processPreviousSibling Function processNextSibling (lines 133–144) first ensures that the current node is not the outputDiv and that nextSibling exists. If so, lines 137–140 adjust the previous and current nodes accordingly and update their highlighting. Function processPrevious-Sibling (lines 147–159) works similarly, ensuring first that the current node is not the outputDiv, that previousSibling exists and that previousSibling is not a text node.

 

Function processParentNode

 

Function processParentNode (lines 181–192) first checks whether the current node’s parentNode is the XHTML page’s body. If not, lines 185–188 adjust the previous and current nodes accordingly and update their highlighting.

 

Common DOM Properties

 

The tables in Figs. 14.27–14.32 describe many common DOM properties and methods. Some of the key DOM objects are Node (a node in the tree), NodeList (an ordered set of Nodes), Document (the document), Element (an element node), Attr (an attribute node) and Text (a text node). There are many more objects, properties and methods than we can possibly list here. Our XML Resource Center ( www.deitel.com/XML/) includes links to various DOM reference websites.

 

Property/Method : Description

           

nodeType : An integer representing the node type.

nodeName : The name of the node.

nodeValue : A string or null depending on the node type.

parentNode : The parent node.

childNodes : A NodeList (Fig. 14.28) with all the children of the node.

firstChild : The first child in the Node’s NodeList.

lastChild : The last child in the Node’s NodeList.

previousSibling : The node preceding this node; null if there is no such node.

nextSibling : The node following this node; null if there is no such node.

attributes : A collection of Attr objects (Fig. 14.31) containing the attributes for this node.

insertBefore : Inserts the node (passed as the first argument) before the existing node (passed as the second argument). If the new node is already in the tree, it is removed before insertion. The same behavior is true for other methods that add nodes.

replaceChild : Replaces the second argument node with the first argument node.

removeChild : Removes the child node passed to it.

appendChild : Appends the node it receives to the list of child nodes.

 

Fig. 14.27 | Common Node properties and methods.

 




 


Locating Data in XML Documents with XPath

 

Although you can use XML DOM capabilities to navigate through and manipulate nodes, this is not the most efficient means of locating data in an XML document’s DOM tree. A simpler way to locate nodes is to search for lists of nodes matching search criteria that are written as XPath expressions. Recall that XPath (XML Path Language) provides a syntax for locating specific nodes in XML documents effectively and efficiently. XPath is a string-based language of expressions used by XML and many of its related technologies (such as XSLT, discussed in Section 14.8).

 

Figure 14.33 enables the user to enter XPath expressions in an XHTML form. When the user clicks the Get Matches button, the script applies the XPath expression to the XML DOM and displays the matching nodes. Figure 14.34 shows the XML document sports.xml that we use in this example. [Note: The versions of sports.xml presented in Fig. 14.34 and Fig. 14.20 are nearly identical. In the current example, we do not want to apply an XSLT, so we omit the processing instruction found in line 2 of Fig. 14.20. We also removed extra blank lines to save space.]

 

1    <?xml version = "1.0" encoding = "utf-8"?>

 

2    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

3          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4              

5    <!-- Fig. 14.33: xpath.html -->

 

6    <!-- Using XPath to locate nodes in an XML document. -->

 

7    <html xmlns = "http://www.w3.org/1999/xhtml">

 

8    <head>

 

9          <title>Using XPath to Locate Nodes in an XML Document</title>

 

10         <style type = "text/css">

 

11               #outputDiv { font: 10pt "Lucida Console", monospace; }

 

12         </style>

 

13         <script type = "text/javascript">

14         <!--

 

15         var doc; // variable to reference the XML document

 

16         var outputHTML = ""; // stores text to output in outputDiv

 

17         var browser = ""; // used to determine which browser is being used

18          

19         // load XML document based on whether the browser is IE7 or Firefox 2

 

20         function loadXMLDocument( url )

21         {

 

22               if ( window.ActiveXObject ) // IE7

23               {


 

3                         // create IE7-specific XML document object

 

4                         doc = new ActiveXObject( "Msxml2.DOMDocument.6.0" );

 

5                         doc.async = false; // specifies synchronous loading of XML doc

 

6                         doc.load( url ); // load the XML document specified by url

 

7                         browser = "IE7"; // set browser

 

8                   } // end if

 

9                   else if ( document.implementation &&

 

10                      document.implementation.createDocument ) // other browsers

11                {

 

12                      // create XML document object

 

13                      doc = document.implementation.createDocument( "", "", null );

 

14                      doc.load( url ); // load the XML document specified by url

 

15                      browser = "FF2"; // set browser

 

16                } // end else

 

17                else // not supported

 

18                      alert( 'This script is not supported by your browser' );

 

19         } // end function loadXMLDocument

41

7             // display the XML document

 

8             function displayDoc()

9             {

 

10                document.getElementById( "outputDiv" ).innerHTML = outputHTML;

 

11         } // end function displayDoc

47

19         // obtain and apply XPath expression

 

20         function processXPathExpression()

21         {

 

22                var xpathExpression = document.getElementById( "inputField" ).value;

 

23                outputHTML = "";

53

32                if ( browser == "IE7" )

33                {

 

34                      var result = doc.selectNodes( xpathExpression );

35                       

 

 

20                      // create IE7-specific XML document object

 

21                      doc = new ActiveXObject( "Msxml2.DOMDocument.6.0" );

 

22                      doc.async = false; // specifies synchronous loading of XML doc

 

23                      doc.load( url ); // load the XML document specified by url

 

24                      browser = "IE7"; // set browser

 

25                } // end if

 

26                else if ( document.implementation &&

 

27                      document.implementation.createDocument ) // other browsers

28                {

 

29                      // create XML document object

 

30                      doc = document.implementation.createDocument( "", "", null );

 

31                      doc.load( url ); // load the XML document specified by url

 

32                      browser = "FF2"; // set browser

 

33                } // end else

 

34                else // not supported

 

35                      alert( 'This script is not supported by your browser' );

 

36         } // end function loadXMLDocument

41

12         // display the XML document

 

13         function displayDoc()

14         {

 

15                document.getElementById( "outputDiv" ).innerHTML = outputHTML;

 

16         } // end function displayDoc

47

24         // obtain and apply XPath expression

 

25         function processXPathExpression()

26         {

 

27                var xpathExpression = document.getElementById( "inputField" ).value;

 

28                outputHTML = "";

53

36                if ( browser == "IE7" )

37                {

 

38                      var result = doc.selectNodes( xpathExpression );

39                       

 

40                      for ( var i = 0; i < result.length; i++ )

38                outputHTML += "<div style='clear: both'>" + 

39                60         result.item( i ).text + "</div>";

40                 

41                } // end if

 

42                else // browser == "FF2"

43                {

 

44                      var result = document.evaluate( xpathExpression, doc, null,

41                            XPathResult.ANY_TYPE, null );

 

42                      var current = result.iterateNext();

43                       

 

44                      while ( current )

45                       {

46                                   70         outputHTML += "<div style='clear: both'>" +                                              

71        current.textContent + "</div>";         

 

3                                current = result.iterateNext();

 

4                         } // end while

 

5                   } // end else

75


 

9                   displayDoc();

 

10         } // end function processXPathExpression

11         // -->

 

12         </script>

 

13   </head>

 

14   <body id = "body" onload = "loadXMLDocument( 'sports.xml' );">

 

15         <form action = "" onsubmit = "return false;">

 

16                 <input id = "inputField" type = "text" style = "width: 200px"/>

 

17               <input type = "submit" value = "Get Matches"

 

18                      onclick = "processXPathExpression()"/>

 

19         </form><br/>

 

20         <div id = "outputDiv"></div>

 

21   </body>

 

22   </html>

 

 



Fig. 14.33 | Using XPath to locate nodes in an XML document.

 

 

                       

<?xml version = "1.0"?>                 

                       

<!-- Fig. 14.34: sports.xml -->         

<!-- Sports Database            -->      

<sports>                    

<game id = "783">              

<name>Cricket</name>                

<paragraph>            

More popular among commonwealth nations.  

</paragraph>                       

</game>                    

<game id = "239">              

<name>Baseball</name>             

<paragraph>            

More popular in America.  

</paragraph>                       

</game>                    

<game id = "418">              

<name>Soccer (Futbol)</name> 

<paragraph>            

Most popular sport in the world.   

</paragraph>                       

</game>                    

</sports>                   

                       

Fig. 14.34 | XML document that describes various sports.

The program of Fig. 14.33 loads the XML document sports.xml (Fig. 14.34) using the same techniques we presented in Fig. 14.26, so we focus on only the new features in this example. Internet Explorer 7 (MSXML) and Firefox 2 handle XPath processing dif-ferently, so this example declares the variable browser (line 17) to store the browser that loaded the page. In function loadDocument (lines 20–40), lines 28 and 36 assign a string to variable browser indicating the appropriate browser.

 

When the body of this XHTML document loads, its onload event calls loadDocument (line 81) to load the sports.xml file. The user specifies the XPath expression in the input element at line 83. When the user clicks the Get Matches button (lines 84–85), its onclick event handler invokes our processXPathExpression function to locate any matches and display the results in outputDiv (line 87).

 

Function processXPathExpression (lines 49–77) first obtains the XPath expression (line 51). The document object’s getElementById method returns the element with the id "inputField"; then we use its value property to get the XPath expression. Lines 54–61 apply the XPath expression in Internet Explorer 7, and lines 62–74 apply the XPath expression in Firefox 2. In IE7, the XML document object’s selectNodes method receives an XPath expression as an argument and returns a collection of elements that match the expression. Lines 58–60 iterate through the results and mark up each one in a separate div element. After this loop completes, line 76 displays the generated markup in outputDiv.

 

For Firefox 2, lines 64–65 invoke the XML document object’s evaluate method, which receives five arguments—the XPath expression, the document to apply the expres-sion to, a namespace resolver, a result type and an XPathResult object into which to place the results. If the last argument is null, the function simply returns a new XPathResult object containing the matches. The namespace resolver argument can be null if you are not using XML namespace prefixes in the XPath processing. Lines 66–73 iterate through the XPathResult and mark up the results. Line 66 invokes the XPathResult’s iterateNext method to position to the first result. If there is a result, the condition in line 68 will be true, and lines 70–71 create a div for that result. Line 72 then positions to the next result. After this loop completes, line 76 displays the generated markup in outputDiv.

 

Figure 14.35 summarizes the XPath expressions that we demonstrate in Fig. 14.33’s sample outputs. For more information on using XPath in Firefox, visit the site developer.mozilla.org/en/docs/XPath. For more information on using XPath in Internet Explorer, visit msdn.microsoft.com/msdnmag/issues/0900/xml/.



Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.