XML technologies / XML / Perl & XML / DOM / XML::DOM
(Excerpt from “Perl & XML” by Erik T. Ray & Jason McIntosh)
The module XML::DOM by Enno Derkson is a good starting point for DOM in Perl: a complete DOM1 implementation with a few convenience methods. It includes the module XML::DOM::Parser, an extension of XML::Parser, for reading an instance of XML::DOM::Document from an XML file. This is the DOM document and its tree. Happily, its objects work exactly as described above.
Our example processes an XHTML file with DOM. It finds the word “Affen” in elements <p> and replaces it with a link to wilhelma.de, the Wilhelma zoological-botanical garden in Stuttgart. A regular expression could do this too, but the example shows finding and creating nodes, and reading and setting values in typical DOM style.
The first part creates a parser object, then asks it to read a file using parsefile( ):
use XML::DOM;
&process_file( shift @ARGV );
sub process_file {
my $infile = shift;
my $dom_parser = new XML::DOM::Parser; # Erzeugung eines Parserobjekts
my $doc = $dom_parser->parsefile( $infile ); # Laß den Parser eine Datei lesen
&add_links( $doc ); # Unsere Änderungen werden durchgeführt
print "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n",
$doc->toString; # Ausgabe des Baums
$doc->dispose; # Freigabe des Speichers
}This returns a reference to an object XML::DOM::Document, giving access to its nodes. Pass it to the function add_links( ), which makes all changes. Finally print the tree by calling toString( ) and release the object. Explicit release is necessary because DOM trees have circular references that could otherwise leak memory.
The next part climbs the tree to process paragraphs:
sub add_links {
my $doc = shift;
# Finde alle <p>-Elemente
my $paras = $doc->getElementsByTagName( "p" );
for( my $i = 0; $i < $paras->getLength; $i++ ) {
my $para = $paras->item( $i );
# Finde alle im <p>-Element enthaltenen Textknoten und bearbeite sie
my @children = $para->getChildNodes;
foreach my $node ( @children ) {
&fix_text( $node ) if( $node->getNodeType eq TEXT_NODE );
}
}
} The function add_links( ) starts by calling the document’s method getElementsByTagName( ). The result is an object of class XML::DOM::NodeList containing every element <p> in the document; searching across arbitrary levels is that easy. The method item( ) lets us process individual elements.
The word is in a text node inside an element <p>. Iterate through its children with getChildNodes( ), which returns an ordinary Perl list in array context, or another object of type XML::DOM::NodeList. We choose the first for variety. Test each node with getNodeType by comparing the result with the constant from XML::DOM named TEXT_NODE( ). Matching nodes go to the function performing the actual change.
The last part processes one text node and replaces “Affen” with a link:
sub fix_text {
my $node = shift;
my $text = $node->getNodeValue;
if( $text =~ /(affen)/i ) {
# Aufteilung des Textknoten in zwei Textknoten um das Wort Affen herum
my( $pre, $orig, $post ) = ( $`, $1, $' );
my $tnode = $node->getOwnerDocument->createTextNode( $pre );
$node->getParentNode->insertBefore( $tnode, $node );
$node->setNodeValue( $post );
# Füge ein <a>-Element zwischen den beiden Knoten ein
my $link = $node->getOwnerDocument->createElement( 'a' );
$link->setAttribute( 'href', 'http://www.wilhelma.de/' );
$tnode = $node->getOwnerDocument->createTextNode( $orig );
$link->appendChild( $tnode );
$node->getParentNode->insertBefore( $link, $node );
# Rekursion auf dem Rest des Textknotens, falls das
# Wort mehrfach vorkommt
fix_text( $node );
}
} The function reads the text string with the method getNodeValue( ). DOM gives read/write access through two redundant properties: the generic method of Node named getNodeValue( ), and the Text class’s specific method getData( ), which would work equally well. Some node types also exist for which getNodeValue( ) simply returns undef, such as elements.
Next split this node in two by creating a text node before the old one. The first receives the text preceding “Affen”; the second the text following it. Notice the object XML::DOM::Document used as a factory for new nodes. This DOM feature handles much housekeeping we would otherwise do ourselves.
Now create an element <a> between the two text nodes. A proper link needs a URL, added through its attribute href. It also needs clickable text: create another text node containing “Affen” and add it to the new element’s children. If “Affen” occurs more than once, process the text node recursively.
Does it work? Try the program on this file:
<?xml version="1.0" encoding="ISO-8859-1"?>
<html>
<head><title>Warum ich Affen mag</title></head>
<body><h1>Warum ich Affen mag</h1>
<h2>Affen sind niedlich</h2>
<p>Affen sind <b>niedlich</b>. Sie sind wie kleine, putzige Versionen
von uns selbst. Sie können unglaubliche Grimassen schneiden und strecken
ihre Zungen heraus.</p>
</body>
</html>This produces the following output:
<?xml version="1.0" encoding="ISO-8859-1"?>
<html>
<head><title>Warum ich Affen mag</title></head>
<body><h1>Warum ich Affen mag</h1>
<h2>Affen sind niedlich</h2>
<p><a href="http://www.wilhelma.de/">Affen</a>
sind <b>niedlich</b>. Sie sind wie kleine, putzige Versionen
von uns selbst. Sie können unglaubliche Grimassen schneiden und strecken
ihre Zungen heraus.</p>
</body>
</html>
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