Hacking Google Maps and Google Earth (ExtremeTech)

(Dana P.) #1

Chapter 5 — Storing and Sharing Information 77


Parsing XML with Perl


You can deal with XML data within Perl in many ways. There are primarily two solutions
within Perl that are useful when thinking about Google Maps applications: the XML::Simple
module and the Document Object Model (DOM). The two systems have similar principles;
understanding the DOM method within Perl will help you to understand the DOM method
used within JavaScript.


The XML::Simplemodule parses an XML document and converts it into a Perl structure
using hashes or arrays as appropriate. You can then access the XML data by using the name of
each tag. For example, Listing 5-13 shows a simple XML::Simpleparser script that dumps
out the structure of the XML document it has just parsed.


Listing 5-13: Using XML::Simple for Parsing XML Documents

use XML::Simple;
use Data::Dumper;


my $xml = XMLin($ARGV[0]);
print Dumper($xml);


The result when parsing the restaurants XML document is shown in Listing 5-14.


Listing 5-14: The Perl Structure of an XML Document

$VAR1 = {
‘restaurant’ => {
‘One on Wharf’ => {
‘points’ => {
‘longitude’ => ‘-0.64’,
‘latitude’ => ‘52.909444’
}
},
‘China Inn’ => {
‘points’ => {
‘longitude’ => ‘-0.6391666’,
‘latitude’ => ‘52.911111’
}
}
},
‘restaurants’ => {}
};

Free download pdf