use strict;
use warnings;
use XML::Twig;
my $FIELDS = {
'AA' => {
'Description' => '',
'Type' => 'Module',
'File' => 'Sample1.pl',
},
'BB' => {
'Description' => 'Initiator',
'Type' => 'Methods',
'File' => 'Sample1.pl',
},
'CC' => {
'Description' => 'Destructor',
'Type' => 'Methods',
'File' => 'Sample2.pl',
'Values' => {
'1' => 'Ignore',
'2' => 'Retry',
'3' => 'Abort'
}
}
};
my $twig = XML::Twig->new (pretty_print => 'indented');
$twig->set_root (my $root = XML::Twig::Elt->new ('Fields'));
AddElements ($root, $FIELDS, 'Function');
$twig->print ();
sub AddElements {
my ($parent, $hash, $type) = @_;
for my $node (sort keys %$hash) {
my $child;
if ($type) {
$child = $parent->insert_new_elt
(last_child => $type, {'Name' => $node});
} elsif ($node =~ /^[0-9]/) {
$child = $parent->insert_new_elt
(last_child => 'Value', {No => $node});
} else {
$child = $parent->insert_new_elt (last_child => $node);
}
if (! ref $hash->{$node}) {
$child->set_text ($hash->{$node});
next;
}
AddElements ($child, $hash->{$node});
}
}
Prints:
<Fields>
<Function Name="AA">
<Description></Description>
<File>Sample1.pl</File>
<Type>Module</Type>
</Function>
<Function Name="BB">
<Description>Initiator</Description>
<File>Sample1.pl</File>
<Type>Methods</Type>
</Function>
<Function Name="CC">
<Description>Destructor</Description>
<File>Sample2.pl</File>
<Type>Methods</Type>
<Values>
<Value No="1">Ignore</Value>
<Value No="2">Retry</Value>
<Value No="3">Abort</Value>
</Values>
</Function>
</Fields>
Perl is environmentally friendly - it saves trees
|