XML technologies / XML / Perl & XML / SAX / SAX event handlers
(Excerpt from “Perl & XML” by Erik T. Ray & Jason McIntosh)
To integrate a typical SAX module, supply an object whose methods handle SAX events. The table lists typical handler methods. The parser passes a hash with event properties, such as the element name and attributes for an element-start event.
Table: Perl SAX handler methods
Method name | Event | Properties |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Notes on handler methods:
Empty elements trigger
start_element( )immediately followed byend_element( ). There is no special empty-element handling.The handler
characters( )can be called repeatedly to deliver a contiguous string in pieces. An entity reference, for example, can make it efficient to report preceding text as one event and the entity content as another. Very long text is also best split into pieces rather than loaded wholly into memory, to avoid excessive consumption.The handler
characters( )is called even for whitespace-only text it considers insignificant. XML treats all characters equally: making no distinction here is simply more efficient.Handlers for processing instructions, comments and CDATA sections are optional. Without them, comments and processing instructions are suppressed. CDATA sections still call
characters(), preserving text.The handlers
start_cdata( )andend_cdata( )receive no data. They indicate whether text delivered throughcharacters( )came from a CDATA section. How text was represented makes no fundamental difference.Without an
entity_reference( )handler, internal entities are automatically resolved and their text or markup becomes part of the document. With anentity_reference( )handler, references remain unresolved and you decide how to handle them.
Now let us write a filter: a processor copying the original with small changes. Ours will:
Convert comments to
<comment>elements.Remove processing instructions.
Remove a
<literal>element’s tag when nested anywhere inside<programlisting>, regardless of nesting depth.
The next example contains the source. Like before, we initialize the parser with handlers, now conveniently packaged in an object named MyHandler . We implement more than before to handle comments, instructions and the prolog.
Example: A filter program
# Initialisierung des Parsers
#
use XML::Parser::PerlSAX;
my $parser = XML::Parser::PerlSAX->new( Handler => MyHandler->new( ) );
if( my $file = shift @ARGV ) {
$parser->parse( Source => {SystemId => $file} );
} else {
my $input = "";
while( <STDIN> ) { $input .= $_; }
$parser->parse( Source => {String => $input} );
}
exit;
#
# Globale Variablen
#
my @element_stack; # Gedächtnis für aktuell offene Elementnamen
my $in_intset; # Flag: Sind wir im internen Bereich der DTD?
###
### Package des Handlers
###
package MyHandler;
#
# Initialisierung des Objekts
#
sub new {
my $type = shift;
return bless {}, $type;
}
#
# Handler für Start eines Elements: Ausgabe des Start-Tag und der Attribute
#
sub start_element {
my( $self, $properties ) = @_;
# Falls wir noch im internen Bereich der DTD sind, müssen wir ihn jetzt abschließen
output( "]>\n" ) if( $in_intset );
$in_intset = 0;
# Elementnamen im Gedächtnis behalten, indem er auf den Stack geschoben wird
push( @element_stack, $properties->{'Name'} );
# Ausgabe des Tags und der Attribute, AUSSER es ist ein <literal>
# innerhalb eines <programlisting>
unless( stack_top( 'literal' ) and
stack_contains( 'programlisting' )) {
output( "<" . $properties->{'Name'} );
# Beachten Sie: Im Hash %attributes geht die Reihenfolge der Attribute verloren.
my %attributes = %{$properties->{'Attributes'}};
foreach( keys( %attributes )) {
output( " $_=\"" . $attributes{$_} . "\"" );
}
output( ">" );
}
}
#
# Behandlung eines Elementendes: Ausgabe des End-Tags, AUSSER es ist von einem
# <literal> innerhalb eines <programlisting>
#
sub end_element {
my( $self, $properties ) = @_;
output( "</" . $properties->{'Name'} . ">" )
unless( stack_top( 'literal' ) and
stack_contains( 'programlisting' ));
pop( @element_stack );
}
#
# Handler für das Event Textdaten
#
sub characters {
my( $self, $properties ) = @_;
# Der Parser hat eventuell Entityreferenzen für uns aufgelöst. Wir müssen sie also
# unsererseits wieder herstellen, um ein gültiges XML-Dokument zu erhalten.
my $data = $properties->{'Data'};
$data =~ s/\&/\&/;
$data =~ s/</\</;
$data =~ s/>/\>/;
output( $data );
}
#
# Handler eines Kommentars: Umwandlung in ein <comment>-Element
#
sub comment {
my( $self, $properties ) = @_;
output( "<comment>" . $properties->{'Data'} . "</comment>" );
}
#
# Handler einer PI: Lösche sie
#
sub processing_instruction {
# Tue nichts!
}
#
# Handler einer internen Entityreferenz (wir möchten sie nicht auflösen)
#
sub entity_reference {
my( $self, $properties ) = @_;
output( "&" . $properties->{'Name'} . ";" );
}
sub stack_top {
my $guess = shift;
return $element_stack[ $#element_stack ] eq $guess;
}
sub stack_contains {
my $guess = shift;
foreach( @element_stack ) {
return 1 if( $_ eq $guess );
}
return 0;
}
sub output {
my $string = shift;
print $string;
} Handlers receive another argument besides the obligatory $self: a hash reference of event properties. Unfortunately, element-start attributes arrive in another hash, losing their original order. Semantically this is harmless: XML says attribute order does not matter. Sometimes, however, we would like to restore it.
For our filter, we might compare input and output with Unix diff. It would flag lines whose only difference is reordered attributes. One solution is replacing diff with Kip Hampton’s module
XML::SemanticDiff, which ignores purely syntactic differences.
As a filter, output should resemble input apart from intended changes. Preserve the prolog, instructions, comments and perhaps unresolved entity references. This requires more handlers than earlier examples concerned only with specific information.
Let us test it with the following input:
Example: Filter input
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE book
SYSTEM "/usr/local/prod/sgml/db.dtd"
[
<!ENTITY schwachsinn "hoo hah blah blah">
]>
<book id="mybook">
<?print newpage?>
<title>Einführung in GRXL</title>
<chapter id="intro">
<title>Was ist GRXL?</title>
<!-- Der Titel sollte schmissiger werden. -->
<para>
Einfach ein weiteres Akronym. Das war unsere ursprüngliche Absicht, aber dann stellte
sich mehr und mehr heraus, wie verblüffend nützlich diese neue Technologie namens
<literal>GRXL</literal> ist. Betrachten Sie das folgende Programm:
</para>
<?print newpage?>
<programlisting>AH aof -- %%%%
{{{{{{ let x = 0 }}}}}}
print! <lineannotation><literal>wow</literal></lineannotation>
oder nicht!</programlisting>
<!-- Welchen Font sollten wir hier benutzen? -->
<para>
Was das Programm macht? Wen kümmert’s? Es sieht einfach cool aus, oder nicht?
Wirklich, ich kann echt nur eines sagen: "&schwachsinn;".
</para>
<?print newpage?>
</chapter>
</book>The next example shows the result.
Example: Filter output
<book id="mybook">
<title>Einführung in GRXL</title>
<chapter id="intro">
<title>Was ist GRXL?</title>
<comment> Der Titel sollte schmissiger werden. </comment>
<para>
Einfach ein weiteres Akronym. Das war unsere ursprüngliche Absicht, aber dann stellte
sich mehr und mehr heraus, wie verblüffend nützlich diese neue Technologie namens
<literal>GRXL</literal> ist. Betrachten Sie das folgende Programm:
</para>
<programlisting>AH aof -- %%%%
{{{{{{ let x = 0 }}}}}}
print! <lineannotation>wow</lineannotation>
oder nicht!</programlisting>
<comment> Welchen Font sollten wir hier benutzen? </comment>
<para>
Was das Programm macht? Wen kümmert’s? Es sieht einfach cool aus, oder nicht?
Wirklich, ich kann echt nur eines sagen: "&schwachsinn;".
</para>
</chapter>
</book> What changed? Comments became <comment> elements and processing instructions vanished. Tags of the <programlisting> element’s nested <literal> element were removed, preserving text. The other <literal> element is unchanged, as are entity references. So far so good, but the XML declaration, the document type declaration and internal subset disappeared. Without the entity declaration for schwachsinn, the document is no longer valid. Our handlers are insufficient.
The German version has another problem: umlauts. Input declares ISO 8859-1, so they are fine there, but removing the XML declaration also removes the encoding declaration.
Copyright © 2003 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “Perl & XML” is subject to the same conditions as the bound edition: the work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de
back to top