Recipe 22.10 Writing XML

22.10.1 Problem

You have a data structure that you'd like to convert to XML.

22.10.2 Solution

Use XML::Simple's XMLout function:

use XML::Simple qw(XMLout);

my $xml = XMLout($hashref);

22.10.3 Discussion

The XMLout function takes a data structure and produces XML from it. For example, here's how to generate part of the book data:

#!/usr/bin/perl -w

use XML::Simple qw(XMLout);

$ds =  {
    book => [
                id      => 1,
                title   => [ "Programming Perl" ],
                edition => [ 3 ],
                id      => 2,
                title   => [ "Perl & LWP" ],
                edition => [ 1 ],
                id      => 3,
                title   => [ "Anonymous Perl" ],
                edition => [ 1 ],

print XMLout($ds, RootName => "books" );

This produces:

  <book id="1">
    <title>Programming Perl</title>
  <book id="2">
    <title>Perl &amp; </title
  <book id="3">
    <title>Anonymous Perl</title>

The rule is: if you want something to be text data, rather than an attribute value, put it in an array. Notice how we used the RootName option to XMLout to specify that books is the top-level element. Pass undef or the empty string to generate an XML fragment with no top-level fragment. The default value is opt.

The id entry in each hash became an attribute because the default behavior of XMLout is to do this for the id, key, and name fields. Prevent this with:

XMLout($ds, RootName => "books", KeyAttr => [  ]);

As with XMLin (see Recipe 22.1), you can identify the hash values that are to become attributes for specific elements:

XMLout($ds, RootName => "books", KeyAttr => [ "car" => "license" ]);

That instructs XMLout to create attributes only for the license field in a car hash.

XML::Simple observes the convention that a hash key with a leading hyphen (e.g., -name) is private and should not appear in the XML output.

22.10.4 See Also

The documentation for the module XML::Simple; Recipe 22.1