Author image Salvador Fandiño García


XML::FromPerl - Generate XML from simple Perl data structures


  use XML::FromPerl qw(xml_from_perl);

  my $doc = xml_from_perl
    [ Foo => { attr1 => val1, attr2 => val2},
      [ Bar => { attr3 => val3, ... },
      [ Bar => { ... },
      "Some Text here",
      [Doz => { ... },
        [ Bar => { ... }, [ ... ] ] ];



This module is able to generate XML described using simple Perl data structures.

XML nodes are declared as arrays where the first slot is the tag name, the second is a HASH containing tag attributes and the rest are its children. Perl scalars are used for text sections.


xml_from_perl $data

Converts the given perl data structure into a XML::LibXML::Document object.

xml_node_from_perl $doc, $data

Converts the given perl data structure into a XML::LibXML::Node object linked to the document passed.



I have not made my mind yet about how to handle XML namespaces other than stating them explicitly in the names or setting the xmlns attribute.

Attribute order

If attribute order is important to you, declare then using Tie::IxHash:

For instance:

  use Tie::IxHash;
  sub attrs {
    my @attrs = @_;
    tie my(%attrs), 'Tie::Hash', @attrs;

  my $doc = xml_from_perl [ Foo => attrs(attr1 => val1, attrs2 => val2), ...];

Otherwise attributes are sorted in lexicographical order.

Memory usage

This module is not very memory efficient. At some point it is going to keep in memory both the original perl data structure and the XML::LibXML one.

Anyway, nowadays that shouldn't be a problem unless your data is really huge.


XML::LibXML, XML::LibXML::Document, XML::LibXML::Node.

Other modules for generating XML are XML::Writer and XML::Generator. Check also XML::Compile.

A related PerlMonks discussion:


Copyright (C) 2017 by Salvador Fandiño <>

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.24.1 or, at your option, any later version of Perl 5 you may have available.