XML technologies / XML / Perl & XML / XML basics: Reading and writing / XML::Writer
(Excerpt from “Perl & XML” by Erik T. Ray & Jason McIntosh)
Compared with everything covered so far, generating XML is child’s play. The shoe is on the other foot: our program already has a data structure under our control. We need not prepare for every uncertainty.
Generating XML is not particularly complicated. We know start-tags, end-tags, attributes and so forth; we just need to dot the i’s and cross the t’s. Are attributes separated by spaces? Are opened elements closed? Do empty elements have closing slashes? We would rather not worry about this. Others have written modules to handle serialization for us.
XML::Writer by David Megginson is an excellent abstract XML-generation interface. Its easy methods generate documents: create a writer object, then call methods to output an XML stream. The following table lists them.
Table: XML::Writer methods
Name | Function |
| Ends the document and checks well-formedness, such as a single root and matching end-tags. These checks are skipped when UNSAFE is set. |
| Outputs an XML declaration at the document’s start. Version “1.0” is hardcoded. |
| Outputs a document type declaration at the document’s start. |
| Outputs an XML comment. |
| Outputs a processing instruction. |
| Outputs a start-tag. First argument: element name; remaining name/value pairs specify attributes. |
| Outputs an empty-element tag, with attributes specified as for |
| Outputs an end-tag. Omit the argument to close the most recently opened element. |
| Outputs an element with text, including both tags and the text between them. |
characters($data) | Outputs text data. |
These methods make generating complete XML documents easy. The following program outputs an HTML file.
Example: HTML generator
use IO;
my $output = new IO::File(">output.xml");
use XML::Writer;
my $writer = new XML::Writer( OUTPUT => $output );
$writer->xmlDecl( 'UTF-8' );
$writer->doctype( 'html' );
$writer->comment( 'Meine niedliche kleine HTML-Seite' );
$writer->pi( 'foo', 'bar' );
$writer->startTag( 'html' );
$writer->startTag( 'body' );
$writer->startTag( 'h1' );
$writer->startTag( 'font', 'color' => 'green' );
$writer->characters( "<Hallo, Welt!>" );
$writer->endTag( );
$writer->endTag( );
$writer->dataElement( "p", "Freut mich, Dich zu sehen." );
$writer->endTag( );
$writer->endTag( );
$writer->end( );Here is the program’s output:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<!-- Meine niedliche kleine HTML-Seite -->
<?foo bar?>
<html><body><h1><font color="green"><Hallo, Welt!></font></h1><p>Freut mich, Dich
zu sehen.</p></body></html>The module offers conveniences: special characters such as ampersand (&) in text automatically become entity references, and attribute values are quoted automatically. During construction, methods such as within_element('body') check context. Here it returns true inside the HTML body, false otherwise.
By default, tags have no separators. Spaces and line endings are often wanted for readability. Setting NEWLINES to true adds a line ending after each end-tag. Setting DATA_MODE has a similar effect. Combining DATA_MODE with DATA_INDENT automatically indents lines to produce a nicely readable document.
XML can organize almost any textual data. With XML::Writer, a pile of information becomes a clearly structured document. For example, the program below converts directory contents into a hierarchical database.
Example: Mapping a directory to XML
use XML::Writer;
my $wr = new XML::Writer( DATA_MODE => 'true', DATA_INDENT => 2 );
&as_xml( shift @ARGV );
$wr->end;
# Rekursive Umwandlung eines einzelnen Verzeichnisses in XML
#
sub as_xml {
my $path = shift;
return unless( -e $path );
# Falls dies ein Verzeichnis ist, gib ein Start-Tag aus, dann den
# Inhalt und dann das End-Tag.
if( -d $path ) {
$wr->startTag( 'directory', name => $path );
# Das Inhaltsverzeichnis von $path wird in ein
# Array geladen.
my @contents = ( );
opendir( DIR, $path );
while( my $item = readdir( DIR )) {
next if( $item eq '.' or $item eq '..' );
push( @contents, $item );
}
closedir( DIR );
# Rekursiver Aufruf für alle Dateien oder Unterverzeichnisse
foreach my $item ( @contents ) {
&as_xml( "$path/$item" );
}
$wr->endTag( 'directory' );
# Alles, was kein Verzeichnis ist, behandeln wir als Datei.
} else {
$wr->emptyTag( 'file', name => $path );
}
} Here is sample output. Note the use of DATA_MODE and DATA_INDENT to improve readability:
$ ~/bin/dir /home/eray/xtools/XML-DOM-1.25
<directory name="/home/eray/xtools/XML-DOM-1.25">
<directory name="/home/eray/xtools/XML-DOM-1.25/t">
<file name="/home/eray/xtools/XML-DOM-1.25/t/attr.t" />
<file name="/home/eray/xtools/XML-DOM-1.25/t/minus.t" />
<file name="/home/eray/xtools/XML-DOM-1.25/t/example.t" />
<file name="/home/eray/xtools/XML-DOM-1.25/t/print.t" />
<file name="/home/eray/xtools/XML-DOM-1.25/t/cdata.t" />
<file name="/home/eray/xtools/XML-DOM-1.25/t/astress.t" />
<file name="/home/eray/xtools/XML-DOM-1.25/t/modify.t" />
</directory>
<file name="/home/eray/xtools/XML-DOM-1.25/DOM.gif" />
<directory name="/home/eray/xtools/XML-DOM-1.25/samples">
<file name="/home/eray/xtools/XML-DOM-1.25/samples/REC-xml-19980210.xml" />
</directory>
<file name="/home/eray/xtools/XML-DOM-1.25/MANIFEST" />
<file name="/home/eray/xtools/XML-DOM-1.25/Makefile.PL" />
<file name="/home/eray/xtools/XML-DOM-1.25/Changes" />
<file name="/home/eray/xtools/XML-DOM-1.25/CheckAncestors.pm" />
<file name="/home/eray/xtools/XML-DOM-1.25/CmpDOM.pm" /> The module XML::Writer is used recursively, step by step. It also works well with object trees: give each object type a “to-string” method making appropriate calls on an XML::Writer object. The module is extremely flexible and useful.
Other output methods
Most parser modules offer their own ways to convert contents into simple, pretty XML strings. For example, document or element objects in XML::LibXML have a method toString( ). More specialized XML applications using the module often use it. Subclasses usually offer corresponding methods implemented through superclass methods. Consult your parser’s documentation for details.
Often even the simple Perl function print is enough. It knows no XML rules, but gives much finer control over every output character. As programming grows trickier, falling back on print can help. We explore this further in Programmer strategies. Never forget to handle the special characters < and & correctly, replacing them with the entity references in the table Entity references valid in XML without declarations. Generous use of CDATA sections is another option.
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