XML technologies / XML / Perl & XML / Working with trees: XPath, XSLT and more / Tree walkers
(Excerpt from "Perl & XML" by Erik T. Ray & Jason McIntosh)
The first tool is a tree walker. As its name suggests, it climbs a tree to find nodes in a specified order, simplifying code so you can focus on processing nodes. It is like employing a trained monkey to pick coconuts: you avoid risking your own skin and need only dig a seawater-filled hole in the beach to keep the harvested nuts moist.
The simplest tree walker is an iterator (sometimes called a cursor ). It moves forward or backward along node references. Forward means the order nodes had in the source text or will have in the final document. The forward algorithm is:
If there is no current node, start at the root.
If the current node has children, move to its first child.
Otherwise, if the node has following siblings, move to the first.
Otherwise, climb through parent nodes until one with following siblings is found.
The algorithm visits each node of a tree or subtree exactly once, ideal for processing an entire subdocument. Recursion can implement it too, but iteration makes it easy to hand control to subroutines by passing the iterator. The following example implements an iterator for DOM trees, with forward and backward methods.
Example: A DOM iterator module
package XML::DOMIterator;
sub new {
my $class = shift;
my $self = {@_};
$self->{ Node } = undef;
return bless( $self, $class );
}
# Einen Knoten vorwärts bewegen
#
sub forward {
my $self = shift;
# Versuche zunächst, den Baum hinunter zu klettern
if( $self->is_element and
$self->{ Node }->getFirstChild ) {
$self->{ Node } = $self->{ Node }->getFirstChild;
# Keine Kindknoten, also begib dich zu den nachfolgenden Geschwistern,
# eventuell zu denen eines Ahnen
} else {
while( $self->{ Node }) {
if( $self->{ Node }->getNextSibling ) {
$self->{ Node } = $self->{ Node }->getNextSibling;
return $self->{ Node };
}
$self->{ Node } = $self->{ Node }->getParentNode;
}
}
}
# Rückwärtsbewegung um einen Knoten
#
sub backward {
my $self = shift;
# Begib dich zu den vorigen Geschwistern, sofern vorhanden,
# ggf. auch zu deren Kindknoten.
if( $self->{ Node }->getPreviousSibling ) {
$self->{ Node } = $self->{ Node }->getPreviousSibling;
while( $self->{ Node }->getLastChild ) {
$self->{ Node } = $self->{ Node }->getLastChild;
}
# Aufwärts
} else {
$self->{ Node } = $self->{ Node }->getParentNode;
}
return $self->{ Node };
}
# Referenz auf den aktuellen Knoten liefern
#
sub node {
my $self = shift;
return $self->{ Node };
}
# Aktuellen Knoten setzen
#
sub reset {
my( $self, $node ) = @_;
$self->{ Node } = $node;
}
# Prüfung, ob der aktuelle Knoten ein Element ist
#
sub is_element {
my $self = shift;
return( $self->{ Node }->getNodeType == 1 );
}The next example tests the iterator, printing a short description of every node, first forward and then backward.
Example: Testing the iterator module
use XML::DOM;
# Initialisierung von Parser und Iterator
my $dom_parser = new XML::DOM::Parser;
my $doc = $dom_parser->parsefile( shift @ARGV );
my $iter = new XML::DOMIterator;
$iter->reset( $doc->getDocumentElement );
# Vorwärtsbewegung mit Ausgabe aller Knoten
print "\nVorwärts:\n";
my $node = $iter->node;
my $last;
while( $node ) {
describe( $node );
$last = $node;
$node = $iter->forward;
}
# und jetzt dasselbe rückwärts
print "\nRückwärts:\n";
$iter->reset( $last );
describe( $iter->node );
while( $iter->backward ) {
describe( $iter->node );
}
# Informationen über einen Knoten ausgeben
#
sub describe {
my $node = shift;
if( ref($node) =~ /Element/ ) {
print 'element: ', $node->getNodeName, "\n";
} elsif( ref($node) =~ /Text/ ) {
print "other node: \"", $node->getNodeValue, "\"\n";
}
} Most tree-based XML parser have built-in tree walkers. For example, XML::LibXML::Node has a method iterator( ), traversing a subtree and passing each node to a subroutine in order. The module Data::Grove::Visitor also implements an iterator.
The following program uses a tree walker to find processing instructions in a document.
Example: Searching for processing instructions
use XML::LibXML;
my $dom = new XML::LibXML;
my $doc = $dom->parse_file( shift @ARGV );
my $docelem = $doc->getDocumentElement;
$docelem->iterator( \&find_PI );
sub find_PI {
my $node = shift;
return unless( $node->nodeType == &XML_PI_NODE );
print "PI gefunden: ", $node->nodeName, "\n";
}Tree walkers are ideal for complete subtrees because they handle all navigation. Often, however, you want particular nodes, such as elements with a given name or attribute value. The more selective approach of XPath may interest you, introduced in XPath.
Copyright © 2003 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from the book "Perl & XML" is subject to the same conditions as the printed edition: the work and all its parts are 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