Don't append the comment node to $elem
but to the parent node. For example, the following script
use XML::LibXML;
my $doc = XML::LibXML::Document->new;
my $root = $doc->createElement("doc");
$doc->setDocumentElement($root);
$root->appendChild($doc->createElement("JJ"));
$root->appendChild($doc->createComment("comment"));
print $doc->toString(1);
prints
<?xml version="1.0"?>
<doc>
<JJ/>
<!--comment-->
</doc>