2013-01-08 95 views
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); 

我不能做到这一点...我如何删除<!-- -->只是没删除包含哪些内容?

回答

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. 
} 
+0

它不能处理这个脚本,有些在编译过程中出现错误,所以请如果任何其他方式..? – user1811486

+0

@ user1811486:请描述您收到的错误。你使用的是什么版本的Perl?仅仅是你需要安装'XML :: Twig'? – Borodin

+0

我目前使用5.8 perl版本,然后XML :: Twig也安装了,然后错误是“无法找到对象方法set_outer_xml'”我该如何解决这个问题? – user1811486