Item Description: A CGI.pm-like module to write XML
Review Synopsis: Robust and convenient, recommended over print
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?
- you are generating XML documents "from scratch"
- you are used to CGI.pm
- XML::Writer is quite mature
Why NOT use XML::Writer?
- another method is more appropriate
- you don't like CGI.pm!
- XML::ValidWriter performs some checks on the output document. Notably it checks whether the elements and attributes are declared in the DTD and whether you are closing the appropriate element.
- XML::AutoWriter automatically generates missing start or end tags, based on the DTD.
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.
#!/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