XML technologies / XML / Perl & XML / XML basics: Reading and writing / Putting the parser to work
(Excerpt from “Perl & XML” by Erik T. Ray & Jason McIntosh)
Enough internal parser details! Let us finally see what can actually be done with parser output. We have already seen a complete parser-generated tree in the example Building an XML tree, so now we will examine the other type. We tap into an XML event stream and run our own code on its events. The result is not especially useful, but nicely illustrates what real XML processors can look like.
At our program’s input sits XML::Parser, internally Expat. This is an event-driven parser like those just described. Instead of loading the whole XML document into memory, it pauses whenever it finds the start or end of a tag. The program checks whether it can do something more or less useful with the supplied data, then lets the parser continue.
Your main task is defining an interface to the program parts handling the different events. Each event type can be assigned its own subroutine, called a handler. We register handlers by setting options when initializing the parser. The next example shows the whole process.
Example: An event-driven XML processor
use XML::Parser;
# Initialisierung des Parsers
my $parser = XML::Parser->new( Handlers =>
{
Start=>\&handle_start,
End=>\&handle_end,
});
$parser->parsefile( shift @ARGV );
my @element_stack; # Speicherung der momentan geöffneten Elemente
# Verarbeitung des Events "Start eines Elements": Gib eine Nachricht aus
#
sub handle_start {
my( $expat, $element, %attrs ) = @_;
# Das Expat-Objekt wird nach der aktuellen Zeilennummer gefragt
my $line = $expat->current_line;
print "Ein Element $element beginnt in Zeile $line!\n";
# Speichere das Element und seine Startposition in Form einer Hashreferenz
# auf dem Stack.
push( @element_stack, { element=>$element, line=>$line });
if( %attrs ) {
print "Das Element besitzt die folgenden Attribute:\n";
while( my( $key, $value ) = each( %attrs )) {
print "\t$key => $value\n";
}
}
}
# Verarbeitung des Events "Ende eines Elements": Gib eine Nachricht aus.
#
sub handle_end {
my( $expat, $element ) = @_;
# Wir holen einfach die gespeicherte Hashreferenz vom Stack. Dabei vertrauen wir
# blind auf den XML-Parser und prüfen nicht, ob das gespeicherte Startelement
# und das jetzt gemeldete Endelement tatsächlich zusammenpassen. Anders als
# unser eigener Parser würde XML::Parser in diesem Fall Zeter und Mordio rufen.
my $element_record = pop( @element_stack );
print "Ein Element $element wird beendet, es begann in Zeile ",
$$element_record{ line }, ".\n";
} The program’s operation is easy to see. We wrote two functions named handle_start( ) and handle_end( ). On calling new( ) we register these functions as handlers for the corresponding events. When parse( ) is called, the parser knows it has handlers for element-start and element-end events. Each subsequent start-tag calls the first handler with the element name and attributes. Similarly, parsing an end-tag calls the other handler with the corresponding element-specific information.
Note that the parser always also passes a reference to an object named $expat . This is an instance of XML::Parser::Expat, an interface to Expat. Through it, the processor can retrieve potentially important information such as the current line number or tree depth. We use it to surprise users with the line number and demonstrate the advantages of a mature XML parser.
Want to see it working? The following output appears when the program receives the customer database from the example An XML document containing SpamChucker’s mailing list:
Ein Element spam-document beginnt in Zeile 2!
Das Element besitzt die folgenden Attribute:
version => 3.5
timestamp => 2002-05-13 15:33:45
Ein Element customer beginnt in Zeile 4!
Ein Element first-name beginnt in Zeile 5!
Ein Element first-name wird beendet, es begann in Zeile 5.
Ein Element surname beginnt in Zeile 6!
Ein Element surname wird beendet, es begann in Zeile 6.
Ein Element address beginnt in Zeile 7!
Ein Element street beginnt in Zeile 8!
Ein Element street wird beendet, es begann in Zeile 8.
Ein Element city beginnt in Zeile 9!
Ein Element city wird beendet, es begann in Zeile 9.
Ein Element state beginnt in Zeile 10!
Ein Element state wird beendet, es begann in Zeile 10.
Ein Element zip beginnt in Zeile 11!
Ein Element zip wird beendet, es begann in Zeile 11.
Ein Element address wird beendet, es begann in Zeile 7.
Ein Element email beginnt in Zeile 13!
Ein Element email wird beendet, es begann in Zeile 13.
Ein Element age beginnt in Zeile 14!
Ein Element age wird beendet, es begann in Zeile 14.
Ein Element customer wird beendet, es begann in Zeile 4.
[... Der Kürze zuliebe überspringen wir die anderen customer...]
Ein Element spam-document wird beendet, es begann in Zeile 2. Again we used an element stack. Storing element names is actually unnecessary because a method on the XML::Parser::Expa t object provides access to the current context list. This is a list of all currently open elements, newest first. A stack is nevertheless useful for additional information such as line numbers. It also demonstrates building our own data structures of arbitrary complexity from events, as a kind of memory of the document parts read.
Many other event types could be handled here. We ignore text, comments and processing instructions in this example, which demonstrates the basic operation of events. That operation is essentially always the same, so we need not cover every type. We will discuss event processing in much greater detail in Event streams.
We cannot finish discussing event processing without mentioning the “Simple API for XML processing,” better known as SAX. This API closely resembles the event model just seen, but is an official W3C-supported standard. Here that means a standardized, canonical set of defined events and a prescribed way of presenting them to the processing program. A standard interface lets you assemble components like Lego bricks and have them work together. If you dislike a parser, use another. Sophisticated tools such as the module family XML::SAX even select a suitable parser automatically according to required capabilities. Whether your XML comes from a database, file or your mother’s shopping list does not matter. SAX excites the Perl community because we were long criticized for ignoring standards and being stubborn; now only the latter charge remains. Look forward to a friendly, detailed discussion of SAX, especially our preferred PerlSAX variant, in SAX.
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