Tag Archives: XML::LibXML

How to generate an XML document with XML::LibXML

For the "note to self" series, or… if I ever need to do this again, I will find this here, here's how to generate an XML document with XML::LibXML. I usually use XML::Simple or XML::TreePP, but this script was already requiring XML::LibXML to parse some XML fragments, so I thought I would use the same module. It wasn't really immediate…

#!/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 %tags = (
    color => 'blue',
    metal => 'steel',
);

for my $name (keys %tags) {
    my $tag = $doc->createElement($name);
    my $value = $tags{$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>

And a copy is also archived at stackoverflow :)