This is a basic Perl problem and nothing special to do with XML::LibXML
. Perl expands simple variables inside quoted strings but not function calls. If you change your code to
print $myXMLdocument->toString(2), "\n";
then you will get the result you need.
Update
You are using the module slightly wrongly. These lines
my $node = $myXMLdocument->createElement("node");
$element->addNewChild('', $node);
$node->addNewChild('', $myXMLdocument->createAttribute( "key" => "value"));
create a new element $node
and then call addNewChild
to add it to $element
. But addNewChild
takes a tag name as its second parameter so Perl is stringifying the $node
object to give the strange tag name that you see. Instead you need
my $node = $myXMLdocument->createElement('node');
$element->addChild($node);
$node->addChild($myXMLdocument->createAttribute(key => 'value'));
or you could stick with addNewChild
and write
my $node = $element->addNewChild('', 'node');
$node->setAttribute(key => 'value');
Update
You might want to consider XML::API
which is my preferred module for writing XML. It allows for concise code, and because it builds a proper XML data tree instead of just appending text to a buffer it is a lot more subtle than it may appear. For more complex structures there is a _goto
method that allows you to go back to nodes in the tree and add more data.
use strict;
use warnings;
use XML::API;
my $xml = XML::API->new;
$xml->myXML_open;
$xml->element_open;
$xml->node({ key => 'value' });
$xml->element_close;
$xml->myXML_close;
print $xml;
output
<?xml version="1.0" encoding="UTF-8" ?>
<myXML>
<element>
<node key="value" />
</element>
</myXML>