Question

I'm using XML::LibXML, I'd like to add a comment such that the the comment is outside the tag. Is it even possible to put it outside the tag? I've tried appendChild, insertBefore | After, no difference ...

     <JJ>junk</JJ> <!--My comment Here!-->

     # Code excerpt from within a foreach loop:
     my $elem     = $dom->createElement("JJ");
     my $txt_node = $dom->createTextNode("junk");
     my $cmt      = $dom->createComment("My comment Here!");

     $elem->appendChild($txt_node);
     $b->appendChild($elem);
     $b->appendChild($frag);
     $elem->appendChild($cmt);

    # but it puts the comment between the tags ...
    <JJ>junk<!--My comment Here!--></JJ>
Was it helpful?

Solution

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top