XML technologies / XML / Perl & XML / Tree-oriented processing / XML::TreeBuilder
(Excerpt from "Perl & XML" by Erik T. Ray & Jason McIntosh)
XML::TreeBuilder is another class for building an object tree, here containing instances of XML::Element. (This class derives from the older class HTML::Element, from the HTML::Tree package.) You can read a tree from a file with XML::TreeBuilder and then use the methods of XML::Element to navigate the tree, extract data, or modify it. We focus on the last option: using accessor methods to build a tree.
Our example manages a simple prioritized to-do list stored in XML, using elements such as “sofort” and “langfristig” for immediate and long-term tasks. If the file is empty or missing, an empty list is initialized. Users can add entries with the options -s or -l (for “sofort” or “langfristig”), supplying a description for each. The program writes the updated file back and displays its contents.
The following example shows the first part of the program, which builds the tree. If the file exists, it is read to build the tree; otherwise, an empty tree is created.
Example: Managing a to-do list, part one
use XML::TreeBuilder;
use XML::Element;
use Getopt::Std;
# Kommandozeilenoptionen
# -s sofort
# -l langfristig
#
my %opts;
getopts( 'sl', \%opts );
# Initialisierung des Baums
my $data = 'data.xml';
my $tree;
# Falls die Dateiexistiert, lies sie und baue den Baum daraus auf
if( -r $data ) {
$tree = XML::TreeBuilder->new( );
$tree->parse_file($data);
# Anderenfalls erzeuge einen leeren Baum
} else {
print "Eine neue Aufgabenliste wird erzeugt.\n";
my @now = localtime;
my $date = $now[4] . '/' . $now[3];
$tree = XML::Element->new( 'aufgabenliste', 'datum' => $date );
$tree->push_content( XML::Element->new( 'sofort' ));
$tree->push_content( XML::Element->new( 'langfristig' ));
}A few comments on initialization are appropriate. The minimal tree for a new file looks like this:
<aufgabenliste datum="DATUM">
<sofort></sofort>
<langfristig></langfristig>
</aufgabenliste> The elements <sofort> and <langfristig> provide anchor points for new tasks. We need three elements in total, created using the constructor of XML::Element, that is, the method new( ). The element name is its first argument. On the first call, we also pass an argument 'datum' => $date, to create an attribute named “datum”. The other nodes must be linked to the first; we use the method push_content( ) to append a node to an element’s child list.
The next part modifies the loaded or newly created tree by inserting a user-specified node. Its position depends on the option (-s or -l). Finally, we use the method as_XML to convert the result back to XML. The next example shows this.
Example: Managing a to-do list, part two
# Eine neue Aufgabe wird eingefügt und das Ergebnis gespeichert
if( %opts ) {
my $item = XML::Element->new( 'aufgabe' );
$item->push_content( shift @ARGV );
my $place;
if( $opts{ 's' }) {
$place = $tree->find_by_tag_name( 'sofort' );
} elsif( $opts{ 'l' }) {
$place = $tree->find_by_tag_name( 'langfristig' );
}
$place->push_content( $item );
}
open( F, ">$data" ) or die( "Konnte die Aufgabenliste nicht speichern." );
print F "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n", $tree->as_XML;
close F; Finally, we display the to-do list, using the method find_by_tag_name( ) to find a named child of the calling element. If several match, it returns a list. Two more methods access element content: attr_get_i( ) for attributes and as_text( ) for element text. The remaining source appears below.
Example: Managing a to-do list, part three
# Ausgabe der Aufgabenliste
print "Aufgabenliste für " . $tree->attr_get_i( 'datum' ) . ":\n";
print "\nSofort zu erledigen:\n";
my $sofort = $tree->find_by_tag_name( 'sofort' );
my $count = 1;
foreach my $item ( $sofort->find_by_tag_name( 'aufgabe' )) {
print $count++ . '. ' . $item->as_text . "\n";
}
print "\nIrgendwann:\n";
my $langfristig = $tree->find_by_tag_name( 'langfristig' );
$count = 1;
foreach my $item ( $langfristig->find_by_tag_name( 'aufgabe' )) {
print $count++ . '. ' . $item->as_text . "\n";
}To test the program, we generated this file with several calls. We added whitespace manually for readability.
<?xml version="1.0" encoding="ISO-8859-1"?>
<aufgabenliste date="7/3">
<sofort>
<aufgabe>Den Goldfisch ins Wasser zurückbringen.</aufgabe>
<aufgabe>Den Blinddarm entfernen lassen.</aufgabe>
</sofort>
<langfristig>
<aufgabe>Den K-2 besteigen.</aufgabe>
<aufgabe>Anzeichen außerirdischen Lebens finden.</aufgabe>
</langfristig>
</aufgabenliste>The screen displays:
Aufgabenliste für 7/3:
Sofort zu erledigen:
1.Den Goldfisch ins Wasser zurückbringen.
2.Den Blinddarm entfernen lassen.
Irgendwann:
1. Den K-2 besteigen.
2. Anzeichen außerirdischen Lebens finden.
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