In addition to the “responseText” property that you saw in the first article, the XMLHttpRequest object offers the “responseXML” property, useful for processing server response, which has been sent back to the client as XML data. Using regular DOM methods, it’s possible to parse basically XML in the client and implement some kind of interaction, either for boosting the capabilities of user interfaces or the application layer itself.
With reference to the above deployed concepts, in conjunction with the sample news rotator that I developed in part one of this series, what I’ll do next is write a simple script that retrieves some headlines from a XML file, then processes them and finally displays the results directly on the browser. Considering that client-side flat text file processing has already been covered, the next example will illustrate how to parse XML files once the corresponding http request has been successfully completed.
As you might guess, in order to get the script parsing XML, first I’ll need to work with sample data served as XML. In this particular case, I’ll define a simple XML file, which contains some headlines to be included in the news rotator. Its definition is the following:
<?xml version="1.0" encoding="iso-8859-1"?> <news> <message> <title>Learn advanced concepts about AJAX and Remote Scripting. Visit DevArticles.com now!</title> <url>http://www.devarticles.com</url> </message> <message> <title>PHP 5.1 now presents new key improvements such as PDO (PHP Data Objects)</title> <url>http://www.php.net</url> </message> <message> <title>Google to continue extending its GoogleMaps API</title> <url>http://www.google.com/apis/maps/documentation/</url> </message> <message> <title>MySQL releases Open Source Database Tools for Macintosh OS X</title> <url>http://www.mysql.com</url> </message> <message> <title>Release of Flash Player 8 allows to develop richer applications and communications</title> <url>http://www.macromedia.com</url> </message> <message> <title>PHP introduces more improvements in regards to SOAP, streams and SPL</title> <url>http://www.php.net</url> </message> </news>
As you can see, the above listed XML file presents a simple structure for defining the appropriate headlines to be displayed, as well as the URLs tied to them. With reference to the document hierarchy, I’ve defined a general <news> tag, which is placed on top of the document tree, and then created a few <message> nodes to wrap up both <title> and <url> child elements. Of course neither style data nor element attributes have been defined for the document, thus its structure is very simple and understandable.