View on
MetaCPAN is shutting down
For details read Perl NOC. After June 25th this page will redirect to
Udo Oji > XML-Constructor-0.01 > XML::Constructor



Annotate this POD

View/Report Bugs
Module Version: 0.01   Source  


XML::Constructor - Generate XML from a markup syntax allowing for the abstraction of markup from code


A simple example of creating an XML document

  use XML::Constructor;

  my $node  = XML::Constructor->generate( 
    parent_node => 'Team',
    data        => [
      {name   => 'Liverpool FC'},
      {league => 'English Premiership'}


The 'toString' method would produce the following XML

    <name>Liverpool FC</name>
    <league>English Premiership</league>

A more advanced example would be:

  use XML::LibXML;     
  use XML::Constructor;

  sub postcode { return { Postcode => 'W11 6TG'} }

  my $surname  = XML::LibXML::Element->new('Surname');

  my $element = XML::Constructor->generate(
   parent_node  => XML::LibXML::Element->new('Details'),
   data    => [
     { Forename => 'Joe' },
     [ 'Phone',  mobile  => '0440' ],
     [ 'Phone',  home    => '0441' ],
     [ 'Address',
       [ 'Location',
         type      => 'Home',
         { 'House'   => undef },
         { 'Street'  => '23 Road Street' },
         { 'City'    => 'London' },
       [ 'Location',
         type      => 'Work',
         { 'House'   => 'GG&H House' },
         { 'Street'  => '23 Road Street' },
         { 'City'    => 'London' },
       { Known_Locations => postcode() }

  print $element->toString;


    <Phone mobile="0440"/>
    <Phone home="0441"/>
      <Location type="Home">
        <Street>23 Road Street</Street>
        <Postcode>W11 6TG</Postcode>
      <Location type="Work">
        <House>GG&amp;H House</House>
        <Street>23 Road Street</Street>
        <Postcode>W11 6TG</Postcode>
        <Postcode>W11 6TG</Postcode>


This package is a wrapper class for XML::LibXML which it uses to generate the XML. It provides an abstraction between presentation and business logic so development of the two can be separated.

This package attempts to satisfy only the most commonly used features of XML. If you require full DOM specification support (without the markup separation) there are better packages to use like XML::Generator of even XML::LibXML directly itself.

That said this package builds and manipulates XML::LibXML instances which you can always decorate after if you so wished.



  XML::Constructor->generate( parent_node => .. , data => [..] )
parameters: parent_node, data
Required: none
Returns: An instance of XML::LibXML::Element [default] | XML::LibXML::Document [if parent_node is an instances of]

'parent_node' can be one of the following

parent_node ( undef )
    if not defined a XML::LibXML::Element instance is created with an element name of ""
parent_node ( XML::LibXML::(Element|Document) )
    parent_node => XML::LibXML::Element->new('Disco')

    accepts XML::LibXML::Element or XML::LibXML::Document instances or any object that inherits from either class
parent_node ( string )
    parent_node => 'Disco'

    the string represents the element's name. A XML::LibXML::Element instance is created
parent_node ( Array ref )
  parent_node => [ Disco => 'date_start', '1974' ]

  Will create a new L<XML::LibXML::Element> node as the parent node. The same markup logic used in L<data> is used to build 
  the parent node. This is useful where you have a situation where the parent node also has attributes.

   The example above will produce a parent node

    <Disco date_start="1974"/>


    <Disco date_start="1974">..</Disco>

    Depending on whether child nodes are attached. Naturally care must be taken as you can easily be tempted to define 
    complex parent nodes but you should try not to do this! Use L<data> instead.

'data' can be one of the following

data ( undef )
  rather pointless but accepted. No markup results in just the parent_node being returned.
data ( Array ref )
  containing markup syntax


  XML::Constructor->toString( parent_node => .. , data => [..] )
parameters: parent_node, data
Required: none
Returns: XML output
  convenience method. Wraps generate and calls 'toString' on XML::LibXML::Element|Document instance


XML::Constructor understands 3 basic types of elements


  { foo => 'bar' }



XML::Constructor takes the key of a hash pairing to be the elements name. If the value of the pairing is a scalar it is append as text to the element. The value may also be a non-scalar but this must reference an array, hash, scalar or a XML::LibXML::Element object


  { foo => XML::LibXML::Element->new('bar') }



non-scalar references

  { foo => { bar => 'baz' }}




  { square => \"hat" }



which is the same as if you passed a normal string. However beware as

  { \"square" => \"hat" }

will produce something similar to


As XML::Constructor will not deference the key.

XML::Constructor supports multi value hashes but note

  { foo => 'bar' , baz => 'taz' }

is NOT equal to

  { foo => 'bar' },{ baz => 'taz' } 

As the former does not guarantee order


  [ 'foo', bar => 1 ]


  <foo bar='1'/>

When an array is encountered a new instances of XML::LibXML::Element is created and the 1st value of the array becomes the elements name. The remaining scalar values of the array become attribute / value pairs within the element. References to array, hash, or XML::LibXML::Element instances are added as child nodes of this element. References to a scalar appends the value to the text field of the element.


  [ 'foo', { bar => baz } ]




  [ 'link', 'rel', 'canonical', 'href', '', \"lovely foo" ]

urrgh let's add some syntax sugar... While

  [ 'link', rel => 'canonical', href => '', \"lovely foo" ]


  <link rel="canonical" href="">lovely foo</link>

Naturally care must be taken but you can mix and match the forms quite safely

  [ 'Phone',  
    mobile    => '0440',
    {foo      => 'bar' }, 
    this      => 'just works', 
    \"both text and element :("


  <Phone mobile="0440" this="just works">
    both text and element :(

XML::LibXML::Element instances

No processing is done. They are simply added to the parent node

Code refs

Because of the precedence terms and operators have in Perl it is possible to embed Perl code into the markup. As long as the term / function returns valid markup XML::Constructor will not croak.

Here's a simple example:

  sub _count { return map{ {'count'.$_ => " $_"} } (0..shift) }

    parent_node => 'sequence',
    data        => [ _count(3) ]);


    <count0> 0</count0>
    <count1> 1</count1>
    <count2> 2</count2>
    <count3> 3</count3>

This is a powerful feature but much care must be taken. See CAVEATS.

scalars ( strings )

strings are appended to the current elements as text. There is an attempt to remove doubly encoded entities before doing so.



Adding a string to the top most node
    parent_node => 'comments',
    data        => [
      \"1st comment",
      { 'account', username => 'fuzzbuzz' },
      \"2nd comment",
      { 'account', username => 'orth' },


    1st comment
    <account username="fuzzbuzz"/>
    2nd comment
    <account username="orth"/>
Fibonacci numbers

Non optimal presentation of the sequence

    my %cache = (qw(0 0 1 1));

    sub _fib {
        my $n = shift;
        return $n if $n < 2;
        $cache{$n} = _fib($n -1) + _fib($n - 2);

    sub fibMarkup {
      my $seed = shift;
      return  map{ {'seq'.$_ => " $cache{$_}"} }sort{$a <=> $b} keys %cache;

  my $number = 8;

  print XML::Constructor->toString(
    parent_node   => ['fibonacci', 'sequence' => $number, f0 =>' 0', f1 => ' 1'],
    data    => [ fibMarkup($number) ]);


  <fibonacci sequence="8" f0=" 0" f1=" 1">
    <seq0> 0</seq0>
    <seq1> 1</seq1>
    <seq2> 1</seq2>
    <seq3> 2</seq3>
    <seq4> 3</seq4>
    <seq5> 5</seq5>
    <seq6> 8</seq6>
    <seq7> 13</seq7>
    <seq8> 21</seq8>


Well not really a bug. Rather a gotcha. One thing you can't do is this

  my $ping  = XML::LibXML::Element->new('Ping');
  print XML::Constructor->toString(
    parent_node => 'missing',
    data        => [

As this will produce


and not the expected 3 'Ping' elements. This is an artifact for XML::LibXML and not this package


There are a number of issues this module does not attempt to satisfy.

Using code references within the markup is a powerful feature BUT there is NO ref counting within the module thus it is possible to fall into a recursive loop.

There is no native support for namespaces. A half way solution is to literally code the namespace.

  [ 'rdf:RDF', 'xmlns:rdf' => "http://...", 'rdf:Genre' => 'http://..' ]


  <rdf:RDF xmlns:rdf=".." rdf:Genre=".."/>

but it's not ideal.

There is limited encoding support. The module attempts to identify double encoding characters but that's it.

If any of these features are deal breakers I advise finding another package.




Judioo, <judioo at>


Please report any bugs or feature requests to judioo at, or through the web interface at I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.


  Heavily depends on L<XML::LibXML>


Copyright 2012 Judioo.

This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License.

See for more information.

syntax highlighting: