XML technologies / XML / Perl & XML / SAX / XML::SAX: The second generation

(Excerpt from “Perl & XML” by Erik T. Ray & Jason McIntosh)

The evolution of SAX parsers raised a problem: how could they all be kept in step with the standard interface? XML::SAX, an excellent collaboration between Matt Sergeant, Kip Hampton and Robin Berjon, solves this problem and also supports SAX Level 2, unlike the other modules.

“What do you mean by keeping them in step with the standard interface?” you may ask. We have praised standard interfaces like SAX for making modules interchangeable. Unfortunately, there is a catch: Perl offers more than one way to implement SAX. SAX was originally designed for Java, a wonderfully type-safe language where every handler argument can be specified precisely. Perl offers no such facility.

This was not a major problem for the older modules discussed so far, which all support the relatively simple SAX 1. A new generation of modules now supports SAX2. It is considerably more complex because it introduces support for namespaces. An element event handler should now receive both the namespace prefix and local name. How should this additional information be passed? As a single string, foo:bar, or as two parameters?

A heated debate arose on the perl-xml mailing list until some members decided to specify a Perl version of SAX. We will soon see how this new SAX2 API is used. To encourage adherence to the new standard, XML::SAX includes a class named XML::SAX::ParserFactory. A factory is an object whose sole purpose is to generate objects of a particular class, here parsers. XML::SAX::ParserFactory helps with parser housekeeping, such as option changes and initialization. Tell the factory what kind of parser you need and it creates an instance.

XML::SAX has significantly shaped XML processing in Perl. It builds on earlier modules by adopting their best features while avoiding some mistakes. A parser base class abstracts routine tasks to ensure compatibility, letting developers focus on important work. Users also benefit from a catalogue of many modules and their capabilities, with simple queries to find a module meeting given requirements. This bold step requires considerable new knowledge. Expect many details in this section; you will see that it is worthwhile!

XML::SAX::ParserFactory

We begin with XML::SAX::ParserFactory, an interface for selecting parsers. If you have used DBI, this class will seem familiar. It fronts all SAX parsers installed on your machine. Request a parser and the factory creates a suitable one. Suppose we have created a package named XML::SAX::MyHandler and want a SAX parser to supply events.

This example obtains a parser and uses it to read a file:

use XML::SAX::ParserFactory;
use XML::SAX::MyHandler;
my $handler = new XML::SAX::MyHandler;
my $parser = XML::SAX::ParserFactory->parser( Handler => $handler );
$parser->parse_uri( "foo.xml" );

The parser selected depends in part on module installation order. By default, the most recently installed parser supporting any capabilities specified through RequiredFeatures is returned. If that is not the one you want, no problem: XML::SAX maintains a catalogue of SAX parsers to choose from. Each new SAX parser registers itself in the catalogue maintained by ParserFactory . If you have installed a parser class named XML::SAX::BobsParser you can obtain an instance using variable $XML::SAX::ParserPackage as follows:

use XML::SAX::ParserFactory;
use XML::SAX::MyHandler;
my $handler = new XML::SAX::MyHandler;
$XML::SAX::ParserPackage = "XML::SAX::BobsParser( 1.24 )";
my $parser = XML::SAX::ParserFactory->parser( Handler => $handler );

Since variable $XML::SAX:ParserPackage contains XML::SAX::BobsParser(1.24), an instance of that class is created. Internally, the ParserFactory loads the class using require( ) and invokes its new( ) method. The number 1.24 specifies the minimum required version. An exception is raised if the class is missing or only an older version is installed.

To list all parser classes registered with XML::SAX use method parsers( ):

use XML::SAX;

my @parsers = @{XML::SAX->parsers( )};

foreach my $p ( @parsers ) {
   print "\n", $p->{ Name }, "\n";
   foreach my $f ( sort keys %{$p->{ Features }} ) {
      print "$f => ", $p->{ Features }->{ $f }, "\n";
   }
}

It returns a reference to a list of hashes. Each hash describes a parser class, including its name and another hash of capabilities. Running the program above reveals two parser classes registered with XML::SAX, both supporting namespaces:

XML::LibXML::SAX::Parser
http://xml.org/sax/features/namespaces => 1

XML::SAX::PurePerl
http://xml.org/sax/features/namespaces => 1

At the time of writing, these were the only two parsers included in the XML::SAX distribution. XML::LibXML::SAX::Parser is a SAX interface built on libxml2, discussed further under Tree-oriented processing. It requires libxml2, a compiled, dynamically loadable library written in C. It is very fast, but without suitable binaries or a compiler its limited portability becomes inconvenient. XML::SAX::PurePerl is entirely written in Perl, as its name suggests. It is fully portable wherever a Perl interpreter exists. These options cover the essential possibilities.

Explicit parser capabilities matter because they guarantee the requested behavior. Suppose you need a validating parser with namespace support. The factory’s require_feature( ) method ensures you get one:

my $factory = new XML::SAX::ParserFactory;
$factory->require_feature( 'http://xml.org/sax/features/validation' );
$factory->require_feature( 'http://xml.org/sax/features/namespaces' );
my $parser = $factory->parser( Handler => $handler );

Alternatively, pass the same information to the factory constructor:

my $factory = new XML::SAX::ParserFactory(
           Required_features => {
                  'http://xml.org/sax/features/validation' => 1
                  'http://xml.org/sax/features/namespaces' => 1
           }
);
my $parser = $factory->parser( Handler => $handler );

If several classes qualify, the most recently installed is used. If none meets the requirements, the factory raises an exception.

To add SAX modules to the catalogue, download and install them. Their installation procedure must know about XML::SAX and register the modules. Registration uses XML::SAX to call method add_parser( ) with a list of module names. To ensure SAX conventions are followed, implement the classes as subclasses of XML::SAX::Base. Later we will explain how to write, install and register a parser.

The SAX2 handler interface

After selecting a parser, write a class with handler methods as before. They process the event streams from a SAX module, just as with the modules already discussed. XML::SAX specifies events and properties precisely, giving handlers considerable control while requiring strict compliance.

Supported handlers are divided into groups. The most familiar are content handlers, responsible for elements and general document information. We have also met entity resolvers and lexical handlers, handling CDATA sections and comments. DTD handlers and declaration handlers handle markup outside the document proper, especially element declarations and entities. XML::SAX also defines a new group called error handlers, invoked on errors.

Namespace support, SAX2’s key innovation, is the most important new feature. Previously SAX parsers treated a qualified name as one string combining prefix and local name. Now namespaces are reported in detail, including where their scope starts and ends, making them much easier to handle.

Content handlers

These handlers focus on document content and are implemented by most SAX programs. A useful new locator reference exposes important parser details. Individual methods also gain namespace properties.

set_document_locator( Lokator )
Called initially to give the handler data-source information. Parameter Lokator references a hash with these properties:

PublicID
Public ID of the entity currently being read.

SystemID
System ID of the entity currently being read.

LineNumber
Line number within the current entity.

ColumnNumber
Column number within the current entity.

This hash is continuously updated. If a handler rejects data, the locator can help produce an error message identifying its position. SAX parsers should supply a locator but need not, so always check whether one exists. Use it only inside an event handler; otherwise results are unpredictable.

start_document( Dokument )
This method is called immediately after set_document_locator( ), before parsing actually begins. Parameter Dokument references an empty hash, since this event currently has no properties.

end_document( Dokument )
This handler is called last to signal end of input or an error terminating parsing. Its return value becomes the parser’s return value from parse( ). Parameter Dokument is again empty.

start_element( Element )
Called when the parser finds a start-tag. Parameter Element is a hash containing element properties, including:

Name
Element name, including any namespace prefix.

Attributes
Reference to an attribute hash. Each attribute has key { NamespaceURI } LocalName and a value referencing a hash of its properties.

NamespaceURI
Element namespace.

Prefix
Namespace prefix.

LocalName
Local part of the qualified name.

Attribute properties include:

Name
Qualified attribute name, prefix plus local name.

Value
Normalized value, with leading and trailing spaces removed.

NamespaceURI
Attribute namespace.

Prefix
Namespace prefix.

LocalName
Local part of the qualified name.

Properties NamespaceURI, LocalName and Prefix are absent if the parser lacks namespace support.

end_element( Element )
Called after processing an element’s content and finding its end-tag, including for empty tags. Parameter Element is a hash with these properties:

Name
Element name, including any namespace prefix.

NamespaceURI
Element namespace.

Prefix
Namespace prefix.

LocalName
Local part of the qualified name.

Properties NamespaceURI , LocalName and Prefix are absent without namespace support.

characters( Text )
Called when text is found. The parser may split text across calls, but must preserve its order. All data in one call must come from the same source. Parameter Text references a hash with a single property named Data, a string containing the text.

ignorable_whitespace( Text )
The term ignorable whitespace means whitespace where an element’s content model allows no text. Line endings and indentation used for readability may be ignored because they are not considered document content. A parser can recognize this only after reading a suitable DTD and must also be validating. If these restrictions seem unclear, these details rarely matter and can safely be set aside. Parameter Text is a parameter with property Data, a string containing the whitespace.

start_prefix_mapping( Mapping )
Called when a namespace scope begins. Parsers without namespace support omit this event but still include prefixes in names. It always precedes the start-tag event of the element opening the scope. Parameter Mapping is a hash reference with these properties:

Prefix
Namespace prefix.

NamespaceURI
Namespace URI mapped to the prefix.

end_prefix_mapping( Mapping )
Called when a namespace scope ends. Parameter Mapping references a hash with this property:

Prefix
Namespace prefix.

The event follows the end-tag event of the element closing the scope.

processing_instruction( PI )
Handles events reporting processing instructions. Parameter PI is a hash reference with these properties:

Target
PI target.

Data
PI data, possibly undef if absent.

skipped_entity( Entity )
Nonvalidating parsers may skip entities instead of resolving them. For an undeclared entity, for example, they may raise an error or ignore its use. This event lets the handler act on the entity, perhaps implementing its own resolution mechanism.

When a parser skips entities, one of these features is set:

  • External parameter entity processing, feature ID "http://xml.org/sax/features/external-parameter-entities".

  • External general entity processing, feature ID "http://xml.org/sax/features/external-general-entities".

Features are represented by URIs that are either present or absent. See Programmer strategies for details.

Parameter Entity is a hash reference with this property:

Name
Name of the skipped entity. Parameter entity names begin with a percent sign (%).

Entity resolvers

By default, XML parsers resolve external entity references without notifying your program. You may wish to change this, for example for entities stored in a database. Whatever your reason, if this handler exists, the parser calls it before attempting resolution itself.

The argument to method resolve_entity( ) is a hash reference with two properties: PublicID, the file’s public identifier, and SystemID, its system identifier, which may be a filesystem path or URI. If the public identifier is undef, none was declared. A system identifier is required.

Lexical event handlers

Implementing these handlers is optional. Usually these events are of no interest, so not every parser supports them, though some fairly complete parsers do. To reproduce the original document faithfully, including comments and CDATA sections, you need such a parser.

Methods in this group include:

  • start_dtd( ) and end_dtd( ), marking the beginning and end of the document type declaration,

  • start_entity( ) and end_entity( ), marking the beginning and end of an expanded entity reference,

  • start_cdata( ) and end_cdata( ), marking the beginning and end of a CDATA section,

  • comment( ) reports a lexical comment. Otherwise parsers ignore comments.

Error event handlers and exceptions

XML::SAX allows customized error handling through this group. Each handler receives one argument, an exception describing the error. The handler is selected by severity according to W3C recommendations. Three levels exist:

warning( )
Handles the least severe exceptions, warnings. Parsing may continue. An unresolved ID reference may trigger a warning while the parser keeps looking for other errors. Without a handler, warnings are ignored.

error( )
These errors are serious but permit continued parsing, for example validation errors. Events can still be generated, though your application may stop. Without a handler, the parser also continues.

fatal_error( )
A fatal error stops document reading immediately; parsing cannot resume, though further application-generated error messages can be collected. Common causes are syntax errors violating XML well-formedness or an unresolvable entity. This is the most severe error category within XML::SAX.

XML requires a parser to terminate on violations of well-formedness or validity. Perl SAX invokes die( ). The program need not terminate, however. Even after a parser invokes die( ), the exception can be caught using eval{} as follows:

eval{ $parser->parse( $uri ) };
if( $@ ) {
# Oh Schreck! Ein Fehler trat auf...
}

Variable $@ is an object with properties describing the error.

These include:

Message 
Textual error description

ColumnNumber 
Column number within the line where the error was detected

LineNumber 
Line number where the error was detected

PublicID 
Public identifier of the entity where the error occurred

SystemID 
System identifier of the entity where the error occurred

An exception does not necessarily mean the XML is faulty. It also occurs when setting an unsupported feature. In that case, probably only property Message is set.

The SAX2 parser interface

After writing a handler, instantiating a parser and configuring its features, the parser must read input. This section explains how with XML::SAX parsers.

Method parse( ) starts processing and accepts an options hash defining handlers, features and input. The following lines set a handler and document:

$parser->parse( Handler => $handler,
             Source => { SystemId => "data.xml" });

Property Handler indicates that the object implements a generic set of handlers. Each group also has its own property, for example: ContentHandler, DTDHandler, EntityResolver and ErrorHandler. Property Handler combines all groups: the object implements all handler methods. Without a handler for a group, the parser ignores its events or handles errors in its own way.

Parameter Source is a hash describing input data with these properties:

CharacterStream 
This filehandle type works from Perl 5.7.2 using PerlIO. No character-set conversion is performed. Instead, function read( ) reads a number of characters. If property CharacterStream is set, ByteStream or SystemId are ignored.

ByteStream 
Specifies a byte stream. Ignored if CharacterStream is set. Conversely, SystemId is ignored when ByteStream is set. If possible, also define Encoding.

PublicId
Optional and possibly ignored; stores a public identifier supplied by the application.

SystemId 
A system-specific source identifier, such as a URI or filesystem path. When reading XML through CharacterStream or ByteStream, setting SystemId may still be necessary for relative entity references.

Encoding 
Store the input encoding here if known.

Another option is Features for setting SAX2-defined features. For example, request special namespace handling. It takes a hash reference with feature names as keys and values such as 0 for off or 1 for on. Alternatively use method set_feature( ). Either variant below obtains a validating parser:

$parser->parse( Features => { 'http://xml.org/sax/properties/validate' => 1 } );
$parser->set_feature( 'http://xml.org/sax/properties/validate', 1 );

For the complete SAX2 feature list, see the SAX documentation. Parsers can expose additional capabilities as custom features. Method get_features( ) lists all features, while get_feature( ) checks support for the feature passed as its argument.

Example: a generator

Implementing a SAX parser is fairly simple. Most work is done by the base class XML::SAX::Base. Derive a subclass and override or implement unsuitable or missing methods. This is convenient, safer and more reliable than rewriting everything. For example, it automatically checks whether a handler implements a method.

The next example shows how easily XML::SAX can create a parser. It is a generator like the one under “Processing non-XML data”, but reads web-server logs instead of Excel spreadsheets. It reads lines like this:

 10.16.251.137 - - [26/Mar/2000:20:30:52 -0800] "GET /index.html HTTP/1.0" 200 16171 

It should produce this XML fragment:

<entry>
<ip>10.16.251.137</ip>
<date>26/Mar/2000:20:30:52 -0800</date>
<req>GET /index.html HTTP/1.0</req>
<stat>200</stat>
<size>16171</size>
</entry>

The example implements the XML::SAX generator. Its first function is parse( ). Normally we would not write a custom parse( ) method, since the base class provides one. But that method expects XML input, unlike our data, so we override it for log files.

Example: SAX generator for web-server logs

package LogDriver;

require 5.005_62;     
use strict;
use XML::SAX::Base;
our @ISA = ('XML::SAX::Base');
our $VERSION = '0.01';

sub parse {
     my $self = shift;
     my $file = shift;
     if( open( F, $file )) {
          $self->SUPER::start_element({ Name => 'server-log' });
          while( <F> ) {
          $self->_process_line( $_ );
          }
          close F;
          $self->SUPER::end_element({ Name => 'server-log' });
    }
}
  
sub _process_line {
     my $self = shift;
     my $line = shift;
    
     if( $line =~
          /(\S+)\s\S+\s\S+\s\[([^\]]+)\]\s\"([^\"]+)\"\s(\d+)\s(\d+)/ ) {
          my( $ip, $date, $req, $stat, $size ) = ( $1, $2, $3, $4, $5 );
    
          $self->SUPER::start_element({ Name => 'entry' });
  
          $self->SUPER::start_element({ Name => 'ip' });
          $self->SUPER::characters({ Data => $ip });
          $self->SUPER::end_element({ Name => 'ip' });
  
          $self->SUPER::start_element({ Name => 'date' });
          $self->SUPER::characters({ Data => $date });
          $self->SUPER::end_element({ Name => 'date' });
  
          $self->SUPER::start_element({ Name => 'req' });
          $self->SUPER::characters({ Data => $req });
          $self->SUPER::end_element({ Name => 'req' });
  
          $self->SUPER::start_element({ Name => 'stat' });
          $self->SUPER::characters({ Data => $stat });
          $self->SUPER::end_element({ Name => 'stat' });
  
          $self->SUPER::start_element({ Name => 'size' });
          $self->SUPER::characters({ Data => $size });
          $self->SUPER::end_element({ Name => 'size' });
  
          $self->SUPER::end_element({ Name => 'entry' });

     }
}
  
1;

Logs are line-oriented, with one entry per line, so a dedicated method _process_line( ) should process each line. It extracts string components and generates XML elements. Method parse( ) simply splits the file into lines and passes them to the processor one at a time.

We never call handler methods directly. We pass data to the corresponding methods of our base class, which forms an abstraction between parser and handler. This is convenient because the base class checks whether the handler requested an event. Its role is to make our work easier.

Let us test the parser. Assuming the module is installed, as explained for an XML::SAX parser in the next section, an application is simple. The example creates a handler class and applies the handler just written to it.

Example: testing the SAX generator

use XML::SAX::ParserFactory;
use LogDriver;
my $handler = new MyHandler;
my $parser = XML::SAX::ParserFactory->parser( Handler => $handler );
$parser->parse( shift @ARGV );

package MyHandler;     

# Objekt mit Optionen initialisieren
#
sub new {
     my $class = shift;
     my $self = {@_};
     return bless( $self, $class );
}

sub start_element {
     my $self = shift;
     my $data = shift;
     print "<", $data->{Name}, ">";
     print "\n" if( $data->{Name} eq 'entry' );
     print "\n" if( $data->{Name} eq 'server-log' );
}

sub end_element {
     my $self = shift;
     my $data = shift;
     print "<", $data->{Name}, ">\n";
}

sub characters {
     my $self = shift;
     my $data = shift;
     print $data->{Data};
}

We use XML::SAX::ParserFactory to demonstrate selecting a registered parser. You can equip the parser with capabilities so it can later be selected by those, rather than only by name.

The handler class simply turns events into XML. Each handler receives a hash reference with corresponding properties; for example, the qualified element name is in property Name. Everything works as expected.

Installing your own parser

Our discussion of XML::SAX would be incomplete without showing how to package a module for installation and correct registration in the catalogue of XML::SAX. This is easy; most work is done by h2xs, originally written to help create Perl modules in C, but now invaluable for pure Perl modules too.

We want an installation routine like CPAN modules use. Start a project with this command:

 h2xs -AX -n LogDriver 

h2xs automatically creates a directory named LogDriver containing these files.

LogDriver.pm
A template for the new module, essentially needing only your subroutines.

Makefile.PL
A Perl program generating the Makefile responsible for installation. Familiar to CPAN users, surely?

test.pl
A test-program template for checking successful installation.

Changes, MANIFEST
Other supporting files for installation and user information.

LogDriver.pm, the module to install, needs little code to satisfy h2xs. Only variable $VERSION must be set.

As with CPAN modules, begin installation with perl Makefile.PL. This generates the Makefile configuring installation. Complete it with commands make and make install.

Any nonstandard installation steps must be programmed in Makefile.PL. Before modification it looks like this:

use ExtUtils::MakeMaker;
WriteMakefile(
     'NAME' => 'LogDriver', # Modulname
     'VERSION_FROM' => 'LogDriver.pm', # Liest Version aus $VERSION
);

The argument to WriteMakeFile( ) is a hash of module properties used in Makefile generation. Add properties to make installation smarter. Here we add:

 'PREREQ_PM' => { 'XML::SAX' => 0 } 

This declares module XML::SAX as a prerequisite of LogDriver. Installation checks its presence; if absent, it reports an error and terminates. The parser must not be installed without its required framework.

Add the following subroutine to Makefile.PL:

sub MY::install {     
     package MY;
     my $script = shift->SUPER::install(@_);
     $script =~ s/install :: (.*)$/install :: $1 install_sax_driver/m;
     $script .= <<"INSTALL";
  
     install_sax_driver :
          \t\@\$(PERL) -MXML::SAX -e "XML::SAX->add_parser(q(\$(NAME)))->save_parsers( )"
  
INSTALL
  
     return $script;
}

This registers the parser in the catalogue maintained by XML::SAX. Our module can now be installed.

  

  

 

 

 

back to top