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
 

Jonathan Stowe

Usenet Archive
Joined
Jan 5, 2000
Messages
37
Reaction score
0
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\
 

Tom Regner

Usenet Archive
Joined
Jul 9, 2004
Messages
23
Reaction score
0
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>
 
U

user

Jonathan Stowe wrote:

In comp.lang.perl.misc wrote:

>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 ...
Thanks Jonathan..

Its a place to start for me ! :)

Regards
AB
 

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
548,042
Messages
3,104,223
Members
248,131
Latest member
Tonypshaw1

Latest Threads

Top