How can I create XML from Perl?

XML::Writer is still maintained (at least, as of February of this year), and it's indeed one of the favorite Perl XML writers out there.

As for describing the syntax, one is better to look at the module's documentation (the link is already in the question). To wit:

use XML::Writer;

my $writer = new XML::Writer();  # will write to stdout
$writer->startTag("greeting", 
                  "class" => "simple");
$writer->characters("Hello, world!");
$writer->endTag("greeting");
$writer->end();

# produces <greeting class='simple'>Hello world!</greeting>

If you want to take a data structure in Perl and turn it into XML, XML::Simple will do the job nicely.

At its simplest:

my $hashref = { foo => 'bar', baz => [ 1, 2, 3 ] };
use XML::Simple;
my $xml = XML::Simple::XMLout($hashref);

As its name suggests, its basic usage is simple; however it does offer a lot of features if you need them.

Naturally, it can also parse XML easily.

EDIT: I wrote this back in Oct 2008, 14 years ago this year. Things have changed since then. XML::Simple's own documentation carries a clear warning:

The use of this module in new code is strongly discouraged. Other modules are available which provide more straightforward and consistent interfaces. In particular, XML::LibXML is highly recommended and you can refer to for a tutorial introduction. XML::Twig is another excellent alternative.

These days, I'd strongly recommend checking those out rather than using XML::Simple in new code.


Just for the record, here's a snippet that uses XML::LibXML.

#!/usr/bin/env perl

#
# Create a simple XML document
#

use strict;
use warnings;
use XML::LibXML;

my $doc = XML::LibXML::Document->new('1.0', 'utf-8');

my $root = $doc->createElement('my-root-element');
$root->setAttribute('some-attr'=> 'some-value');

my %elements = (
    color => 'blue',
    metal => 'steel',
);

for my $name (keys %elements) {
    my $tag = $doc->createElement($name);
    my $value = $elements{$name};
    $tag->appendTextNode($value);
    $root->appendChild($tag);
}

$doc->setDocumentElement($root);
print $doc->toString();

and this outputs:

<?xml version="1.0" encoding="utf-8"?>
<my-root-element some-attr="some-value">
    <color>blue</color>
    <metal>steel</metal>
</my-root-element>

Tags:

Xml

Perl