Chapter 5 — Storing and Sharing Information 81
Listing 5-18: Processing XML in JavaScript
var request = GXmlHttp.create();
request.open(“GET”, “/examples/xmlbasic2.xml”, true);
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
var xmlDoc = request.responseXML;
var points = xmlDoc.getElementsByTagName(“points”);
for (var i = 0; i < points.length; i++)
{
var xmlpoint = new
GPoint(parseFloat(points[i].getAttribute(“longitude”)),
parseFloat(points[i].getAttribute(“latitude”)));
var xmlmarker = new GMarker(xmlpoint);
map.addOverlay(xmlmarker);
}
}
}
request.send(null);
This is just a fragment of the full HTML document that generates the map, but it demon-
strates the DOM access methods built into JavaScript for processing XML documents.
The script works as follows:
1.A new GXmlHttpobject is created.
2.The XML file is downloaded.
3.Once the file has been loaded (when the GXmlHttpobject reaches readyState 4), the
rest of the processing can begin.
4.The list of pointselements from the document is extracted. The xmlDocis the
name of the object that contains the XML data. The getElements ByTagName()
method to this object returns a list of XML objects that contain the data in each
<points>...</points>tag.
5.A new GPointobject is created based on the attribute value of the longitudeand
latitudeattributes for each pointselement. Attributes are extracted from a given
tag (in this case one of the <points>tag objects) using the getAttribute()
method.
6.The GPointis used to create a new marker.
7.The marker is added to the Google Map.