Section 4.3. Back on the Client: Mining the XML


4.3. Back on the Client: Mining the XML

Here's where the fun begins. The client code in Example 4-5 shows how to mine the data fields from the XML document that the server sends.

Example 4-5. The client code

 <!DOCTYPE HTML PUBLIC "-//w3c//dtd html 4.0 transitional//en"> <html> <head>     <STYLE type="text/css">         .borderless {  color:black; text-align:center; background:powderblue;                 border-width:0;border-color:green;  }     </STYLE>     <title>function</title>     <SCRIPT language="JavaScript" type="text/javascript">         var req;         function convertToXML( ) {             var key = document.getElementById("key");             var keypressed = document.getElementById("keypressed");             keypressed.value = key.value;             var url = "/ajaxcodeconverter-lab2/response?key=" + escape(key.value);             if (window.XMLHttpRequest) {                 req = new XMLHttpRequest( );             }             else if (window.ActiveXObject) {                 req = new ActiveXObject("Microsoft.XMLHTTP");             }             req.open("Get",url,true);             req.onreadystatechange = callback;             req.send(null);         }         function nonMSPopulate( ) {             xmlDoc = document.implementation.createDocument("","", null);             var resp = req.responseText;             var parser = new DOMParser( );             var dom = parser.parseFromString(resp,"text/xml");             decVal = dom.getElementsByTagName("decimal");             var decimal = document.getElementById('decimal');             decimal.value=decVal[0].childNodes[0].nodeValue;             hexVal = dom.getElementsByTagName("hexadecimal");             var hexadecimal = document.getElementById('hexadecimal');             hexadecimal.value=hexVal[0].childNodes[0].nodeValue;             octVal = dom.getElementsByTagName("octal");             var octal = document.getElementById('octal');             octal.value=octVal[0].childNodes[0].nodeValue;             hyperVal = dom.getElementsByTagName("hyper");             var hyper = document.getElementById('hyper');             hyper.value=hyperVal[0].childNodes[0].nodeValue;             binaryVal = dom.getElementsByTagName("binary");             var bin = document.getElementById('bin');             bin.value=binaryVal[0].childNodes[0].nodeValue;         }         function msPopulate( ) {             var resp = req.responseText;             var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");             xmlDoc.async="false";             xmlDoc.loadXML(resp);             nodes=xmlDoc.documentElement.childNodes;             dec = xmlDoc.getElementsByTagName('decimal');             var decimal = document.getElementById('decimal');             decimal.value=dec[0].firstChild.data;             hexi = xmlDoc.getElementsByTagName('hexadecimal');             var hexadecimal = document.getElementById('hexadecimal');             hexadecimal.value=hexi[0].firstChild.data;             oct = xmlDoc.getElementsByTagName('octal');             var octal = document.getElementById('octal');             octal.value=oct[0].firstChild.data;             bin = xmlDoc.getElementsByTagName('binary');             var binary = document.getElementById('bin');             binary.value=bin[0].firstChild.data;             hypertextml = xmlDoc.getElementsByTagName('hyper');             var hyper = document.getElementById('hyper');             hyper.value=hypertextml[0].firstChild.data;         }         function callback( ) {             if (req.readyState==4) {                 if (req.status == 200) {                     if (window.XMLHttpRequest) {                         nonMSPopulate( );                     }                     else if (window.ActiveXObject) {                         msPopulate( );                     }                 }             }             clear( );         }         function clear( ) {             var key = document.getElementById("key");             key.value="";         }     </SCRIPT> </head> <body>     <H1>         <CENTER>AJAX CHARACTER DECODER</CENTER>     </H1>     <H2>         <CENTER>Press a key to find its value.</CENTER>     </H2>     <form name="form1" action="/ajaxcodeconverter-lab2" method="get">     <table border="2" bordercolor="black" bgcolor="lightblue" valign="center"            align="center">         <tr>             <td align="center">                 Enter Key Here ->                 <input type="text"  name="key" maxlength="1" size="1"                        onkeyup="convertToXML( );">             </td>         </tr>     </table>     <br>     <table  border="1" valign="center" align="center">         <tr>             <td align="center" colspan="5">                 Key Pressed:&nbsp;                 <input  type="text" readonly                         maxlength="1" size="1">             </td>         </tr>         <tr>             <td align="center">&nbsp;&nbsp;Decimal&nbsp;&nbsp;</td>             <td align="center">Hexadecimal</td>             <td align="center">&nbsp;&nbsp;&nbsp;Octal&nbsp;&nbsp;&nbsp;</td>             <td align="center">                 &nbsp;&nbsp;&nbsp;&nbsp;Binary&nbsp;&nbsp;&nbsp;&nbsp;             </td>             <td align="center">                 &nbsp;&nbsp;&nbsp;&nbsp;HTML&nbsp;&nbsp;&nbsp;&nbsp;             </td>         </tr>         <tr>             <td align="center"><input  type="text" readonly                  maxlength="6" size="6"></td>             <td align="center"><input  type="text" readonly                  maxlength="6" size="6"></td>             <td align="center"><input  type="text" readonly                  maxlength="6" size="6"></td>             <td align="center"><input  type="text" readonly                  maxlength="8" size="8"></td>             <td align="center"><input  type="text" readonly                  maxlength="6" size="6"></td>         </tr>     </table>     </form> </body> </html> 

Wow, that's a chunk of code. Let's break it up into two parts: first we'll look at the XML parsing, then at writing the data to the fields.

4.3.1. XML Parsing with JavaScript

Remember, it all starts with our callback( ) function in JavaScript:

 function callback( ) {     if (req.readyState==4) {         if (req.status == 200) {             if (window.XMLHttpRequest) {                 nonMSPopulate( );             }             else if (window.ActiveXObject) {                 msPopulate( );             }         }         clear( );     } } 

Remember how convertToXML( ) had to determine whether the browser was Internet Explorer or something else? We have the same problem again here. When callback( ) is invoked, it must check to see whether we are running ActiveXObject (Internet Explorer) or XMLHttpRequest (all other major browsers).

If the browser is Internet Explorer, we run msPopulate( ) to strip out the data from the XML. Otherwise, we run nonMSPopulate( ). What's the difference? It has to do with how we get an XML parser and with the API that parser presents to us. Firefox, Mozilla, and Safari all use new DOMParser( ) to get a built-in parser that can parse XML, and it's rumored that Opera will support this soon. Internet Explorer, on the other hand, uses new ActiveXObject("Microsoft.XMLDOM") to get the Microsoft XML parser.

Although Ajax works on most browsers in their current released states, it's entirely fair to say that the problem of cross-browser compatibility is the Achilles' heel of web applications.

4.3.2. Populating the Form on a Microsoft Browser

The msPopulate( ) function is reproduced in Example 4-6.

Example 4-6. The msPopulate( ) function

  1  function msPopulate( ) {  2      var resp = req.responseText;  3  4      var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");  5      xmlDoc.async="false";  6      xmlDoc.loadXML(resp);  7  8      dec = xmlDoc.getElementsByTagName('decimal');  9      var decimal = document.getElementById('decimal'); 10      decimal.value=dec[0].firstChild.data; 11 12      hexi = xmlDoc.getElementsByTagName('hexadecimal'); 13      var hexadecimal = document.getElementById('hexadecimal'); 14      hexadecimal.value=hexi[0].firstChild.data; 15 16      oct = xmlDoc.getElementsByTagName('octal'); 17      var octal = document.getElementById('octal'); 18      octal.value=oct[0].firstChild.data; 19 20      bin = xmlDoc.getElementsByTagName('binary'); 21      var binary = document.getElementById('bin'); 22      binary.value=bin[0].firstChild.data; 23 24      hypertextml = xmlDoc.getElementsByTagName('hyper'); 25      var hyper = document.getElementById('hyper'); 26      hyper.value=hypertextml[0].firstChild.data; 27  } 

Here, we use the built-in browser functions that I have touted as a programmer power play. We start by getting the ActiveXObject called Microsoft.XMLDOM (line 4). Next, we load the response from the servlet into the XML document (line 6).

Now we can mine the document for the data. First we get the data between the <decimal></decimal> tags. To do this, we first retrieve the XML data field information, by calling getElementsByTagName(elementName) (line 8); this function returns the array of child nodes belonging to the element (parent node) associated with the given tag. After we get the array of child nodes, we can reference the first element in the child node by calling firstChild. We then obtain the value of the child node by referencing the data field. So, to sum it up, we get our decimal value from dec[0].firstChild.data.

If you are parsing a document that contains multiple tags with the same tag name, you can access any of the values by indexing the array. For example, if you had another <decimal>value</decimal> entry, you would index it with this call: dec[1].firstChild.data.


After obtaining the decimal value from the XML, line 10 updates the decimal form element. We've now retrieved one value from the XML and displayed it on the page. We continue on in this fashion until all of our data fields are updated with the values retrieved from the XML DOM sent from the servlet.

4.3.3. Populating the Form on Other Browsers

The code for handling non-Microsoft browsers, shown in Example 4-7, is similar; there are some minor differences in the parser API, but that's about it.

Example 4-7. The nonMSPopulate( ) function

  1  function nonMSPopulate( ) {  2      var resp = req.responseText;  3      var parser = new DOMParser( );  4      var dom = parser.parseFromString(resp,"text/xml");  5  6      decVal = dom.getElementsByTagName("decimal");  7      var decimal = document.getElementById('decimal');  8      decimal.value=decVal[0].childNodes[0].nodeValue;  9 10      hexVal = dom.getElementsByTagName("hexadecimal"); 11      var hexadecimal = document.getElementById('hexadecimal'); 12      hexadecimal.value=hexVal[0].childNodes[0].nodeValue; 13 14      octVal = dom.getElementsByTagName("octal"); 15      var octal = document.getElementById('octal'); 16      octal.value=octVal[0].childNodes[0].nodeValue; 17 18      hyperVal = dom.getElementsByTagName("hyper"); 19      var hyper = document.getElementById('hyper'); 20      hyper.value=hyperVal[0].childNodes[0].nodeValue; 21 22      binaryVal = dom.getElementsByTagName("binary"); 23      var bin = document.getElementById('bin'); 24      bin.value=binaryVal[0].childNodes[0].nodeValue; 25  } 

We create a new DOMParser (line 3), then we create a DOM on line 4 from the XML string that we received from the servlet. Next, we get the element between the <decimal></decimal> tags (line 6) by calling dom.getElementByTagName("decimal"). After retrieving the decimal form element from our HTML document, we retrieve the value sent to us in the XML and use it to set the appropriate field:

 decimal.value=decVal[0].childNodes[0].nodeValue; 

The reference to decVal[0] gets the data between the <decimal></decimal> tags. If we had two sets of <decimal></decimal> tags, we would reference the second set as decVal[1].

This is what the data should look like in the response sent from the servlet:

 <converted-values>     <decimal>97</decimal>     <hexadecimal>0x61</hexadecimal>     <octal>0141</octal>     <hyper>&amp;0x61;</hyper>     <binary>1100001B</binary> </converted-values> 




Ajax on Java
Ajax on Java
ISBN: 0596101872
EAN: 2147483647
Year: 2007
Pages: 78

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