Perl CookbookPerl CookbookSearch this book

22.10. Writing XML

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.

Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.