LibXML - 插入评论

Cra*_*igP 1 perl libxml2 xml-libxml

我正在使用XML :: LibXML,我想添加一个注释,使得注释不在标记之内.甚至可以把它放在标签之外?我试过appendChild,insertBefore | 之后,没有区别......

     <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>
Run Code Online (Sandbox Code Playgroud)

nwe*_*hof 5

不要将注释节点附加$elem到父节点.例如,以下脚本

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);
Run Code Online (Sandbox Code Playgroud)

版画

<?xml version="1.0"?>
<doc>
  <JJ/>
  <!--comment-->
</doc>
Run Code Online (Sandbox Code Playgroud)