XML technologies / XML / Perl & XML / Event streams / XML::Parser
(Excerpt from “Perl & XML” by Erik T. Ray & Jason McIntosh)
Another early parser is XML::Parser, the first fast, efficient CPAN parser. Some capabilities appeared in XML basics: Reading and writing. Its built-in “stream” mode deserves closer examination, so let us return to a sensible event-stream example.
We will use XML::Parser to read addresses from an XML document, including contact names, streets and telephone numbers. As the parser loads the file, our handler saves the information in a special structure for later processing. Once parsing finishes, the program sorts addresses by contact name and prints an HTML table.
The next example shows the input document. Its outer root element is <liste>, containing four <kontakt> elements. Each contains a name, telephone number and address.
Example: An address-book file
<?xml version="1.0" encoding="ISO-8859-1"?>
<liste>
<kontakt>
<name><vorname>Taddäus</vorname><nachname>Troll</nachname></name>
<telefon>0711 5623723</telefon>
<adresse>
<strasse>Schwanstr. 8</strasse>
<stadt>Stuttgart</stadt><plz>70432</plz>
</adresse>
</kontakt>
<kontakt>
<name><vorname>Beppo</vorname><nachname>Brem</nachname></name>
<adresse>
<strasse>Dahlienweg 17</strasse>
<plz>80131</plz>
<stadt>München</stadt>
</adresse>
<telefon>089 736862</telefon>
</kontakt>
<kontakt>
<name><nachname>Kabel</nachname>
<vorname>Heidi</vorname></name>
<adresse>
<strasse>Am Alsterwasser 11</strasse>
<stadt>Hamburg<stadt><plz>20457</plz>
</adresse>
<telefon>040 342946</telefon>
</kontakt>
<kontakt>
<adresse>
<strasse>Schnabelgasse 27b</strasse>
<stadt>Stuttgart</stadt><plz>70113</plz>
</adresse>
<name><vorname>Willi</vorname><nachname>Reichert</last></nachname>
<telefon>0711 2987234</telefon>
</kontakt>
</liste> This simple structure suits event processing. Each <kontakt> start-tag signals a new structure for storing data. A </kontakt> end-tag marks a complete record ready for storage. Children of <kontakt> elements clearly tell the handler what information arrives and where to store it. Contacts are independent: there are no links forward or backward in the document.
The next example contains the program. It first initializes the parser with references to subroutines handling individual events. These are called callbacks because you write them first and the parser later calls them to handle events.
After initialization, global variables are defined to store information read from XML elements. They give the handlers a memory. Saving information for later processing is often called saving state. The parser later returns to that state information.
After logic for reading data and invoking the parser, the rest consists of handlers. We handle five events: document start and end, element start and end, and text. Comments, processing instructions and other events are ignored.
Example: A program displaying addresses
# Initialisierung des Parsers mit Referenzen auf die Handlerfunktionen
#
use XML::Parser;
my $parser = XML::Parser->new( Handlers => {
Init => \&handle_doc_start,
Final => \&handle_doc_end,
Start => \&handle_elem_start,
End => \&handle_elem_end,
Char => \&handle_char_data,
});
#
# Globale Variablen
#
my $record; # Zeiger auf einen Hash mit Elementinhalten
my $context; # Name des aktuellen Elements
my %records; # Menge von Adreßeinträgen
#
# Daten durch Parser lesen lassen
#
my $file = shift @ARGV;
if( $file ) {
$parser->parsefile( $file );
} else {
my $input = "";
while( <STDIN> ) { $input .= $_; }
$parser->parse( $input );
}
exit;
###
### Handlerfunktionen
###
#
# Wenn die Verarbeitung beginnt, wird der Kopf einer HTML-Tabelle ausgegeben.
#
sub handle_doc_start {
print "<html><head><title>Adressen</title></head>\n";
print "<body><h1>Adressen</h1>\n";
}
#
# Speicherung von Elementnamen und Attributen
#
sub handle_elem_start {
my( $expat, $name, %atts ) = @_;
$context = $name;
$record = {} if( $name eq 'kontakt' );
}
# Zeichendaten werden dem jeweils aktuellen Element zugewiesen
#
sub handle_char_data {
my( $expat, $text ) = @_;
# Minimale Behandlung von HTML-Sonderzeichen
$text =~ s/&/&/g;
$text =~ s/</</g;
$record->{ $context } .= $text;
}
#
# Falls dies ein <kontakt>-End-Tag ist, erzeuge einen neuen Datensatz.
#
sub handle_elem_end {
my( $expat, $name ) = @_;
return unless( $name eq 'kontakt' );
my $fullname = $record->{'nachname'} . "," . $record->{'vorname'};
$records{ $fullname } = $record;
}
#
# Ende der Daten, gib die gelesenen Adressen aus.
#
sub handle_doc_end {
print "<table border='1'>\n";
print "<tr><th>Name</th><th>Telefon</th><th>Adresse</th></tr>\n";
foreach my $key ( sort( keys( %records ))) {
print "<tr><td>" . $records{ $key }->{ 'vorname' } . ' ';
print $records{ $key }->{ 'nachname' } . "</td><td>";
print $records{ $key }->{ 'telefon' } . "</td><td>";
print $records{ $key }->{ 'strasse' } . ', ';
print $records{ $key }->{ 'stadt' } . ', ';
print $records{ $key }->{ 'plz' } . "</td></tr>\n";
}
print "</table>\n</div>\n</body></html>\n";
} Understanding the program requires focusing on the handlers. All handlers called by XML::Parser receive as their first argument a reference to an Expat parser object. Developers can query it for additional information, such as the current input line. Further arguments depend on event type: a start-tag handler receives the element name as its second argument, followed by attribute names and values.
Our handlers use global variables. If you dislike them, create an object storing the information internally. There are good reasons: globals are hard to debug and risky with threads. Anonymous code references can then serve as handlers, invoking object methods and forwarding data. We retain globals here to keep the example understandable.
The first handler, handle_doc_start, runs when parsing begins, conveniently allowing preparation before actual processing. It could initialize the handler for reuse. Here it prints an HTML table header and receives no special arguments.
The next handler, handle_elem_start, runs when an element starts. Besides the required Expat reference, it receives the element name $name and the variable %atts, a hash of attribute names and values. (Hash key order is lost; if attribute order matters, use a variable @atts instead, extracting name/value pairs in a loop.) This example does not use attributes, but we keep the possibility in mind.
The handler starts processing an element by saving its name in $context. This always holds the most recently opened element’s name, or the current element if it has no children. We need it later for text processing. If the opened element has type <kontakt> , a hash named %record is also initialized to hold values such as surname and street.
The third handler, handle_char_data, handles text. Its second argument supplies text as $text . Its task is simple: store the text in $record->{ $context }. This works because the start-element handler initialized these variables. Note that we append $text rather than overwriting existing values. XML::Parser calls this handler at line endings. Multiline element text therefore triggers several calls, one per line.
Note: Reading text this way is typical of Perl, but may surprise XML purists. XML normally ignores line endings; indeed, all whitespace is insignificant. It is simply text to handle uniformly.
Without appending, only the last line would remain as the value.
Unsurprisingly, handle_elem_end runs when an element ends. Its second argument is the element name, as for the start handler. Usually nothing is required except for the <kontakt> element. Its address information is complete and can be saved in another hash, keyed by full names to simplify later sorting. Sorting must wait until every address has been collected. Without sorting, we could output each address as HTML immediately and avoid storage.
Finally comes the handler handle_doc_end. It runs after the whole document has been read. Usually it performs cleanup, such as releasing resources. Here we still need to sort addresses by name, output them as HTML, and close the table.
This example was simple: essentially a flat sequence of entries like table rows. XML is generally much more complex. Some document formats depend on parents, grandparents or even more distant ancestors. Remembering ancestry requires a more sophisticated structure, shown in a later example.
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