Search code examples
perllibxml2xml-libxml

Perl XML::LibXML: how to access comment nodes


For the life of me I can't figure out the proper code to access the comment lines in my XML file. Do I use findnodes, find, getElementByTagName (doubt it).

Am I even making the correct assumption that these comment lines are accessible? I would hope so, as I know I can add a comment.

The type number for a comment node is 8, so they must be parseable.

Ultimately, what I want tot do is delete them.

my @nodes = $dom->findnodes("//*");

foreach my $node (@nodes) {
  print $node->nodeType, "\n";
}

<TT>
 <A>xyz</A>
 <!-- my comment -->
</TT> 

Solution

  • According to the XPath spec:

    • * is a test that matches element nodes of any name. Comment nodes aren't element nodes.

    • comment() is a test that matches comment nodes.

    Untested:

    for $comment_node ($doc->findnodes('//comment()')) {
       $comment_node->parentNode->removeChild($comment_node);
    }