10.2 Transforming XML 237
use XML::Parser;
$p = new XML::Parser(Handlers => { Start => \&start });
$p->parsefile($ARGV[0]);
sub start {
$tag = $[1];
%attributes = @;
if ($tag eq "Interview") {
print("Weight $attributes{Weight}\n");
}
}
Program 10.14 Parsing XML attributes
called XML::Parser. Suppose that we would like to obtain theWeightat-
tribute of everyInterviewin an XML document that looks like this:
This task can be accomplished by using program 10.14. Theusestatement
imports the XML::Parser module. If this statement fails, then this module
has not yet been installed. You can install it by using thecpancommand or
its equivalent as described in subsection 10.2.1.
The next two statements of the program construct the XML parser and
parse the document. There are several styles for parsing. The style for pro-
cessing the XML document one element at a time is called the “handlers”
style.Handlersare Perl procedures that are invoked as various kinds of data
are encountered in the XML document. AStarthandler is invoked whenever
an XML element is first encountered. There are many kinds of handler that
will be discussed later. In this case the Start handler is a procedure called
start.
The initial\&in front ofstartis telling Perl that one is passing thestart