1

我想从 XML 文件中收集所有标签。如何仅删除评论语法?

XML 文件:

<xml>
<contrib-group>
<contrib contrib-type="author">
<name>
<surname>Holt</surname>
<given-names> Maurice<!--<xref ref-type="fn" rid="fnI_1"><sup>1</sup></xref>--></given-names>
</name>
</contrib>
</contrib-group>
</xml>

我需要输出为:

<xml>
<contrib-group>
<contrib contrib-type="author">
<name>
<surname>Holt</surname>
<given-names> Maurice<xref ref-type="fn" rid="fnI_1"><sup>1</sup></xref></given-names>
</name>
</contrib>
</contrib-group>
</xml>

如何删除评论.. 不删除包含?

脚本:

#!/usr/bin/perl
use warnings;
use strict;
use XML::Twig;

open(my $output , '>', "split.xml") || die "can't open the Output $!\n";
my $xml = XML::Twig->new( twig_handlers => { xref => sub{comments => 'drop'} } );
$xml->parsefile("sample.xml");
$xml->print($output);

我做不到......我怎样才能<!-- -->只删除而不删除包含?

4

1 回答 1

6
#!/usr/bin/perl
use warnings;
use strict;

use XML::Twig;

open my $output , '>', 'split.xml' or die "Can't open: $!\n";
my $xml = XML::Twig->new( comments      => 'process',       # Turn on comment processing
                          twig_handlers =>
                              { '#COMMENT' => \&uncomment }
                        );
$xml->parsefile('sample.xml');
$xml->print($output);

sub uncomment {
    my ($xml, $comment) = @_;
    $comment->set_outer_xml($comment->text);                # Replace the comment with its contents.
}
于 2013-01-08T09:26:00.727 回答