【问题标题】:LibXML - Inserting a CommentLibXML - 插入注释
【发布时间】:2013-10-16 18:36:24
【问题描述】:

我正在使用 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>

【问题讨论】:

    标签: perl libxml2 xml-libxml


    【解决方案1】:

    不要将注释节点附加到$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>
    

    【讨论】:

      猜你喜欢
      • 2013-02-06
      • 1970-01-01
      • 2013-05-06
      • 2017-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-29
      相关资源
      最近更新 更多