use warnings; use strict; use XML::LibXML; my $hash = { 'root' => { 'item1' => { 'item1a' => 'n1', 'item1b'=>'jh' } } }; my $dom = XML::LibXML::Document->createDocument(); # recursively convert hashes to elements my $frag = $dom->createDocumentFragment(); my $hash2el; $hash2el = sub { my ($n,$h) = @_; for my $key (sort keys %$h) { my $el = $dom->createElement($key); if (ref $h->{$key} eq 'HASH') { $hash2el->($el, $h->{$key}) } else { $el->appendText( ''.$h->{$key} ) } $n->appendChild($el); } }; $hash2el->($frag, $hash); # either a single root node, or multiple nodes in a new root my @roots = $frag->nonBlankChildNodes(); if (@roots==1) { $dom->setDocumentElement( $roots[0] ); } elsif (@roots>1) { my $root = $dom->createElement('root'); $root->appendChild($frag); $dom->setDocumentElement( $root ); } print $dom->toString(1); __END__ n1 jh