XML technologies / XML / Perl & XML / XML basics: Reading and writing / XML::LibXML
(Excerpt from “Perl & XML” by Erik T. Ray & Jason McIntosh)
XML::LibXML is another interface to a library actually written in C, much like XML::Parser. In this case it is libxml2 from the GNOME project. Unlike XML::Parser, this newer parser also supports the most important standard for tree-based processing of XML documents, the Document Object Model (DOM).
DOM is another widely cited XML standard. For the tree-based approach, it plays the same role as SAX does for event streams. If you look forward to climbing trees in your program and think you may reuse individual components in another application, or consider various possible data sources, the same advice applies: stick to the standard interface. We will discuss DOM and the thinking behind standard interfaces in greater detail in DOM.
Let us now see this other parser in action. Showing only one parser example would be a mistake when there are so many. Again, we use a fairly simple example that essentially just calls the parser and demonstrates how to harness its power. Let us write another analysis program, similar to the one in An event-driven XML processor, this time outputting a frequency distribution of elements in the document.
The following example shows this program. Since we set no options, the parser runs with its defaults. Essentially, it reads the document from a filehandle and returns a DOM object: a structure of well-defined objects. Our program finds the document element, traverses the entire tree, and builds a hash of element names and their frequency counts.
Example: A program for calculating a frequency distribution
use XML::LibXML;
use IO::Handle;
# Initialisierung des Parsers
my $parser = new XML::LibXML;
# Ein Dateihandle wird eröffnet und der Parser gestartet
my $fh = new IO::Handle;
if( $fh->fdopen( fileno( STDIN ), "r" )) {
my $doc = $parser->parse_fh( $fh );
my %dist;
&proc_node( $doc->getDocumentElement, \%dist );
foreach my $item ( sort keys %dist ) {
print "$item: ", $dist{ $item }, "\n";
}
$fh->close;
}
# Verarbeitung eines XML-Knotens: Update des zugehörigen Zählers
# und Verarbeitung der Kindelemente
#
sub proc_node {
my( $node, $dist ) = @_;
return unless( $node->nodeType eq &XML_ELEMENT_NODE );
$dist->{ $node->nodeName } ++;
foreach my $child ( $node->getChildnodes ) {
&proc_node( $child, $dist );
}
} Note that here we use a filehandle object from the class IO::Handle rather than a filename. As you may know, Perl filehandles often have a certain magic and subtle capabilities. They provide a uniform way to feed character data into your program from very different sources: disk files, open network sockets, keyboard input, databases, or any other data stores. Once opened, a filehandle always offers the same interface, regardless of the data source. This fits very well with our XML-oriented philosophy of writing code that is as flexible and reusable as possible. Ultimately, an XML document does not care where it is read from, so why should we restrict ourselves to a single way of reading data?
After parsing, we obtain a document object. It provides a method returning a reference to the document element—the element at the root of the object tree. We feed this element into a recursive subroutine called proc_node( ), which processes one element after another and maintains a hash variable. Recursion is always a natural technique for XML processing because documents have a fractal nature: the rules for an element are essentially independent of its depth or position in the document. This holds even for the root element, which represents the document as a whole (apart from the prolog). Note the check of “node type.” It distinguishes elements from all other parts of the document, such as text data or processing instructions.
For each element object, the function calls its method getChildnodes( ) to process the child elements. This call marks the essential difference between event-driven and tree-based processing. Instead of handing control to the event stream, which calls subroutines to shovel data into our program in a somewhat unpredictable order, we take responsibility for navigating the document ourselves. Normally, we start at the document element and climb the tree from there, traversing each element’s children starting with the first, just as the parser would. Here, however, we are free to traverse the document differently and need not follow the parser. We can move backwards, jump around, introduce loops—the sky is the limit. Here is the output of the sample program analyzing a book chapter written in DocBook XML:
$ xfreq < ch03.xml
chapter: 1
citetitle: 2
firstterm: 16
footnote: 6
foreignphrase: 2
function: 10
itemizedlist: 2
listitem: 21
literal: 29
note: 1
orderedlist: 1
para: 77
programlisting: 9
replaceable: 1
screen: 1
section: 6
sgmltag: 8
simplesect: 1
systemitem: 2
term: 6
title: 7
variablelist: 1
varlistentry: 6
xref: 2Outputting the result takes only a few lines of source code, but obtaining the data requires a lot of work. Thanks to the library written in C, however, it happens very quickly.
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