Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

22. XML > 22.3. Parsing XML into SAX Events

22.3. Parsing XML into SAX Events

Problem

You want to receive Simple API for XML (SAX) events from an XML parser because event-based parsing is faster and uses less memory than parsers that build a DOM tree.

Solution

Use the XML::SAX module from CPAN:

use XML::SAX::ParserFactory;
use MyHandler;

my $handler = MyHandler->new( );
my $parser = XML::SAX::ParserFactory->parser(Handler => $handler);

$parser->parse_uri($FILENAME);
# or
$parser->parse_string($XML);

Logic for handling events goes into the handler class (MyHandler in this example), which you write:

# in MyHandler.pm
package MyHandler;

use base qw(XML::SAX::Base);

sub start_element {   # method names are specified by SAX
  my ($self, $data) = @_;
  # $data is hash with keys like Name and Attributes
  # ...
}

# other possible methods include end_element( ) and characters( )

1;

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint