XML technologies / XML / Perl & XML / XML basics: Reading and writing / XML::Parser
(Excerpt from “Perl & XML” by Erik T. Ray & Jason McIntosh)
Writing a parser takes a great deal of work. Only extensive testing tells you whether you have covered everything. Perhaps you are a mutant who enjoys developing and optimizing parser code at the lowest level? No? Then your program may be slow and consume resources. Fortunately, many high-quality, free, easy-to-use XML parsers already exist, presumably written by such mutants. Years of work combining Perl and XML have produced many already-invented wheels for you to use.
Where do Perl programmers find ready-made modules? At the Comprehensive Perl Archive Network (CPAN), of course: a widely mirrored archive of free open-source software in and for Perl. If you do not know CPAN, leave your ivory tower and become a practical programmer. You will find countless modules by people long involved with Perl and XML, freely sharing their tools with the world.
Note: Do not imagine CPAN as a catalog of finished solutions for every XML application. Think of a toolbox or building blocks to assemble and configure into your own application. Some modules address specific applications such as SOAP or RSS, but most are general-purpose. You will probably adapt a generic module to your needs. We will show how easy this is, with several ways to integrate a module into your application.
XML parsers differ mainly in two respects. The first is parsing style, how a parser handles XML, for example by building a data structure or producing an event stream. Another important property is its degree of standards compliance, ranging from highly specialized solutions to meticulous compliance. The balance is gradually shifting toward standards such as SAX or DOM as the Perl community agrees how to implement them.
The module XML::Parser is the great-great-grandfather of Perl XML processors. It offers many parsing styles, making it versatile, although rather nonstandard. Being the first efficient XML parser on the Perl horizon, it became widely used and earned a special place in our hearts. It remains useful today. Admittedly, the API of XML::Parser is not standardized and is sometimes fussy, but it simply works. It parses documents at reasonable speed and with flexibility. Programmers often choose the first working solution they find, Perl hackers included, and tolerate minor blemishes. Almost all older Perl XML modules therefore build on XML::Parser.
Since about 2001, other XML parsers have appeared with faster, more standards-oriented cores. We will examine them shortly, but first spend more time with good old XML::Parser .
In XML’s early days, a skilled programmer named James Clark wrote a C parser called Expat. (Note: James Clark is highly respected in the XML community for tirelessly advancing XML and its standards through freely available tools. Much of his work is at www.jclark.com. He also edits W3C recommendations for XSLT and XPath available at www.w3.org.) Expat’s speed, efficiency and reliability made it the early tool of choice. Larry Wall himself wrote its low-level API, bridging XML and Perl, and named it XML::Parser::Expat. He then derived XML::Parser as a convenient, general-purpose parser for everyone. XML::Parser is now maintained by Clark Cooper and underpins many XML modules.
The success of XML::Parser undoubtedly comes from binding an existing C implementation. We saw the work needed for even a simple Perl parser. Try ours on a large XML document: you will wait a long time for it to confirm the document’s well-formedness. Pure-Perl solutions are portable, but cannot match a C racer such as Expat. Fortunately, module users need not know whether the internals are C or Perl. Many such modules exist because Perl’s XS interface makes them relatively straightforward to create. (Note: For XS details, see the manual page perlxs and chapter 25 of Programming Perl.)
Example: Checking well-formedness, revised
To demonstrate XML::Parser, return to checking document well-formedness. With XML::Parser, this becomes simple, as the next example shows.
Example: Checking well-formedness with XML::Parse
use XML::Parser;
my $xmlfile = shift @ARGV; # Die Datei, die wir prüfen wollen
# Initialisierung eines Parserobjekts und Lesen der Datei
my $parser = XML::Parser->new( ErrorContext => 2 );
eval { $parser->parsefile( $xmlfile ); };
# Falls ein Fehler gemeldet wurde, gib ihn aus; andernfalls verkünde den Erfolg
if( $@ ) {
$@ =~ s/at \/.*?$//s; # Zeilennummer des Moduls entfernen
print STDERR "\nFEHLER in '$xmlfile':\n$@\n";
} else {
print STDERR "'$xmlfile' enthält ein wohlgeformtes XML-Dokument\n";
} First create an object of type XML::Parser to do the work. Unlike a static method, an object can be configured once and reused with the same settings, reducing initialization overhead. It preserves settings and access to Expat routines while parsing files, then cleans everything up.
Next call parsefile( ) inside an eval block, because XML::Parser handles errors drastically. Without this eval-block, an error would terminate the program without a chance to clean up. Then inspect $@ for an error message. If present, strip the module line number identifying where the error was detected, then print a message.
When initializing, set the option ErrorContext => 2. XML::Parser has options controlling parsing. This one is passed directly to Expat, which retains the last two lines before an error and supplies them as context if necessary. The printed message thus includes both the error type and an illustrative document excerpt.
Here is a sample diagnostic from our checker, which we named xwf for “XML well-formedness checker”.
$ xwf ch01.xml
FEHLER in 'ch01.xml':
not well-formed (invalid token) at line 66, column 22, byte 2354:
<chapter id="dorothy-in-oz">
<title>Lions, Tigers & Bears</title>
=====================^Notice how easily the parser initializes and how good the results are. What is not visible here, but apparent when running it, is speed: the response arrives in a fraction of a second.
Configuration offers several approaches. You need not read a file: parse( ) can analyze a text string. Alternatively, the option NoExpand => 1 suppresses resolution of external entities and can install your own resolver. Our checker could thus avoid checking external files.
A well-formedness checker is useful whenever you regularly work with XML files, but barely scratches the surface of XML::Parser . The next section shows the parser’s chief task: moving data into a program. How that happens depends on the selected style.
Parsing styles
XML::Parser supports styles suited to different development strategies. They do not change how XML is read, but radically change how data reaches your program. Want a persistent document structure? Or calls to your own functions? Both are possible. Select the style during initialization with the constructor attribute Style. Available choices are:
Debug
Writes the document to
STDOUT, indenting nested elements more deeply. parse( ) returns no special result.
Tree
Builds a hierarchical tree for the program, representing all elements and data as nested hashes and arrays.
Object
Like
Tree, returns a reference to hierarchical document data, but using objects representing XML components rather than plain hashes and arrays.
Subs
Here you supply callback functions for particular elements, naming functions after the elements they handle. Functions reside in a package selected with the option
pkg. At the start-tag of an element<fooby>, the parser looks in that package forfooby( ), and at the end-tag for_fooby( ). It passes essential information, including content and attributes, for the function to process.
Stream
As in
Subs, define callbacks for XML components, but categorized more generally than by element name. Functions are called handlers for events such as the start of any element, character data or a processing instruction. Select their package withHandlersor by callingsetHandlers( ).
Subklassenname
You may also subclass
XML::Parserand use the full class name as style, containing at least one::. This suits specialized parser-like APIs. The moduleXML::Parser::PerlSAXuses this to implement SAX.
The next program uses XML::Parser with the style Tree. It reads the entire XML document into a data structure, then gives it to the program for processing.
Example: Building an XML tree
use XML::Parser;
# Initialisierung des Parsers und Lesen einer Datei
$parser = new XML::Parser( Style => 'Tree' );
my $tree = $parser->parsefile( shift @ARGV );
# Serialisierung der Struktur
use Data::Dumper;
print Dumper( $tree );In Tree mode, parsefile( ) returns a reference to arrays and hashes representing the document. We use Data::Dumper, a convenient data-structure serializer, to print it. The next example is possible input:
Example: A sample XML file
<preferences>
<font role="console">
<fname>Courier</name>
<size>9</size>
</font>
<font role="default">
<fname>Times New Roman</name>
<size>14</size>
</font>
<font role="titles">
<fname>Helvetica</name>
<size>10</size>
</font>
</preferences>This input produces the following output, indented and slightly reformatted for readability:
$tree = [
'preferences', [
{}, 0, '\n',
'font', [
{ 'role' => 'console' }, 0, '\n',
'size', [ {}, 0, '9' ], 0, '\n',
'fname', [ {}, 0, 'Courier' ], 0, '\n'
], 0, '\n',
'font', [
{ 'role' => 'default' }, 0, '\n',
'fname', [ {}, 0, 'Times New Roman' ], 0, '\n',
'size', [ {}, 0, '14' ], 0, '\n'
], 0, '\n',
'font', [
{ 'role' => 'titles' }, 0, '\n',
'size', [ {}, 0, '10' ], 0, '\n',
'fname', [ {}, 0, 'Helvetica' ], 0, '\n',
], 0, '\n',
]
]; Dissecting this structure is much easier than writing a parser. The document must be 100 percent well-formed, since the parser returned data instead of terminating with “die”. In Event streams we examine the Stream style of XML::Parser, and in Tree-oriented processing we discuss trees and objects further.
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