removing comments from XML using Perl XML::DOM

U

user

Hi

How do i remove comments from a DOM object ?

I tried searching the man pages XML::DOM, XML::DOM::Comment and
XML::DOM::Document but could not find anything

The code used to parse the file is below ..

use strict;
use warnings;

use XML::DOM;

my $file = shift ;
my $parser = new XML::DOM::parser;
my $doc = $parser->parsefile ($file);

# How do I remove the comments from $doc ?


TIA
AB
 
J

Jonathan Stowe

In said:
Hi

How do i remove comments from a DOM object ?

I tried searching the man pages XML::DOM, XML::DOM::Comment and
XML::DOM::Document but could not find anything

I'm not sure that XML::DOM is the way to go here you may be better off
using XML::Twig or XML::SAX, but as you asked:


use strict;
use warnings;

use XML::DOM;

my $file = shift;
my $parser = new XML::DOM::parser;
my $doc = $parser->parsefile($file);

remove_comments($doc);

print $doc->toString();

sub remove_comments {
my ($doc) = @_;
foreach my $node ( $doc->getChildNodes() ) {
if ( $node->getNodeType() == ELEMENT_NODE ) {
remove_comments($node);
}
elsif ( $node->getNodeType() == COMMENT_NODE ) {
$doc->removeChild($node);
}
}
}

This comes with the caveat that I have only tested it with limited data.

/J\
 
T

Tom Regner

Hi

How do i remove comments from a DOM object ?
tested, works, you need a few more moudles though:

code:
----------------------------------
use XML::DOM;
use XML::XQL;
use XML::XQL::DOM;

my $file = shift ;
my $parser = new XML::DOM::parser;
my $doc = $parser->parsefile ($file);
my @comments = $doc->xql('//comment()');
for my $node (@comments) {
my $parent = $node->getParentNode();
$parent->removeChild($node);
}
$doc->printToFile ("out.xml");
__END__
1) code speichern als xql.pl

2 Datei anlegen: test.xml
<xml>
<test></test>
<!-- comment 1 -->
<test><!-- comment 2 -->
</test>
</xml>

3) ausführen:
[1256]tom@margo perl $ perl ./xql.pl test.xml

4) Ausgabe (out.xml):
<xml>
<test/>

<test>
</test>
</xml>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top