http://www.perlmonks.org?node_id=31565

Item Description: A CGI.pm-like module to write XML

Review Synopsis: Robust and convenient, recommended over print

Description

XML::Writer generates XML using an interface similar to CGI.pm. It allows various checks to be performed on the document and takes care of special caracter encoding.

Why use XML::Writer?

Why NOT use XML::Writer?

Related modules

XML::ValidWriter and XML::AutoWriter both aim at emulating XML::Writer interface:

XML::Generator and XML::Handler::YAWriter are 2 other modules doing XML generation

Personal notes

At the moment XML::Writer seems to be the most mature and efficient module to generate XML. Of course a lot of the transformation modules such as XML::Simple, XML::DOM and XML::Twig can also be used;

Of course plain print's can also be used, but I think that XML::Writer is a lot more convenient and adds some control over the generated XML.

Example

#!/bin/perl -w use strict; use XML::Writer; use IO; my $doc = new IO::File(">doc.xml"); my $writer = new XML::Writer(OUTPUT => $doc); $writer->startTag("doc", class => "simple"); # tag + att $writer->dataElement( 'title', "Simple XML Document");# text elt $writer->startTag( "section"); $writer->dataElement( 'title', "Introduction", no => 1, type => "intro"); $writer->startTag( "para"); $writer->characters( "a text with"); $writer->dataElement( 'bold', "bold"); $writer->characters( " words."); $writer->endTag( "para"); $writer->endTag(); # close section $writer->endTag(); # close doc $writer->end(); # check that the doc # has only one element $doc->close(); # fixed (was $output->close(); ) as suggested by the p +ost below