2013-10-16 73 views
1

我正在使用XML :: LibXML,我想添加注释,以使注释位于标记之外。它甚至有可能把它放在标签之外吗?我试过appendChild,insertBefore |之后,没有区别...LibXML - 插入注释

 <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> 

回答

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); 

打印

<?xml version="1.0"?> 
<doc> 
    <JJ/> 
    <!--comment--> 
</doc> 
+0

再次感谢@nwellnhof! – CraigP