10.07.2015 Views

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

172CHAPTER 9 ■ XML PARSING WITH PERLThe code that produced this output is similar <strong>to</strong> the earlier Data::Dumper example. Noticethe use of the KeyAttr option in the call <strong>to</strong> the XMLin() subroutine.#!/usr/bin/perluse strict;use XML::Simple;use Data::Dumper;my $xml = XMLin('./example1.xml',forcearray=> [ 'vehicle' ],KeyAttr=>['email' ] TheSansMonoConNormal);print Dumper($xml);■Note Take a look through the perldoc for XML::Simple. The documentation for this module is quite goodand actually helps <strong>to</strong> sort out the options in<strong>to</strong> categories such as important, handy, advanced, and others.Parsing XML with XML::SAXXML::SAX is a stream-based parser. When XML is parsed by XML::SAX, each new elementencountered signals an event <strong>to</strong> the parser. XML::SAX hands off the processing for thatevent <strong>to</strong> the appropriate method. It’s your responsibility <strong>to</strong> write handlers for events asthey are passed by XML::SAX. For example, XML::SAX will encounter the beginning of anXML tag. When it does so, it passes the information along in an event stream <strong>to</strong> the parser.This parser implements a number of handlers <strong>to</strong> work with that event. The data from theevent is usually placed inside a hash, but that depends on the type of event.There are parsers already written for XML::SAX. Two such handlers are XML::LibXML::SAX::Parser and XML::SAX::Pure<strong>Perl</strong>. XML::LibXML::SAX::Parser requires the libxml2 libraryand is written in C. As you might guess by the name, XML::SAX::Pure<strong>Perl</strong> is written entirely in<strong>Perl</strong>. These two handlers, along with others for XML::SAX, may be already installed on your system.In practice, you’ll find that you’ll be writing your own parser more often than not.This program prints a list of the available parsers on your system:#!/usr/bin/perluse XML::SAX;use strict;my @parsers = @{XML::SAX->parsers()};foreach my $parser (@parsers) {print "--> ", $parser->{ Name }, "\n";}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!