Hacking Google Maps and Google Earth (ExtremeTech)

(Dana P.) #1

Chapter 5 — Storing and Sharing Information 73


Generating and Parsing XML


Programmers familiar with HTML will understand the basic concept behind XML. Both are
technically identical to the structure of Standard Generalized Markup Language (SGML). All
three rely on the same basic structure.

When supplying information for use with Google Maps, you need to generate comparatively
simple XML documents, with perhaps only a couple of nested levels of information. Generally,
the key is to generate information that can easily be parsed by JavaScript to display information
and provide a list of map points or additional data.

Before seeing the processes for creating and parsing XML, it is worth looking at the main
points and key terms of the XML format. XML is a superset of the Standard General Markup
Language (SGML), which is also the source for the HTML standard used for web pages.
XML enables you to structure data in a neutral format that can be generated and understood
by many different platforms and environments.

The basic component of XML is the tag. This is a single word enclosed in angle brackets. For
example, you could create a tag for restaurant information using this:
<restaurant>

Tags are actually defined in pairs: the opening tag and the closing tag, which has the same text,
but a leading forward slash:
</restaurant>

Within a tag is the tag data. This could be actual information, for example:
<restaurant>One on Wharf</restaurant>

Or it can be further tags:
<restaurant>
<name>One on Whard</name>
<city>Grantham</city>
</restaurant>

Finally, tags can also contain attributes (additional pieces of information that help to define
further information about a tag or its contents). For example, you could rewrite the preceding
code as
<restaurant name=”One on Wharf” city=”Grantham”>A nice restaurant.</restaurant>

Because XML files are basic text, generating the files is quite straightforward, although care
must be taken to ensure that the structure of the XML is correct. Parsing an XML document
is more difficult, because you have to take into account the different parts of the structures.
Fortunately there are techniques and extensions for both operations that make it easy to gener-
ate and parse the contents of an XML file.
Free download pdf