4

我正在使用 XML::Twig 模块从 XML 文件中删除所有注释。示例文件可以是 -

<?xml version="1.0" encoding="UTF-8"?>
<Node_A>
node A content 1
<!-- One Line Comment A1-->
<![CDATA[this portion within the two comments is being
REMOVED which is not the intention]]>
<!-- Two Line Comment
Two Line Comment-->
node A content 3
<!-- Two Line Comment
Two Line Comment-->
<![CDATA[this portion within the two comments is being
REMOVED which is not the intention]]>
<!-- Two Line Comment
Two Line Comment-->
<![CDATA[
this portion is fine]]>

<Node_B> node B content
<Node_C> node c content
</Node_C>
<!-- One Line Comment -->
some data one
<!-- Multi  Line Comment
Line 3Comment
1Line Comment
2Line Comment
Line 5Comment
Line Comment-->
some data again two 
<!-- Multi  Line Comment
Line 3Comment
Line 5Comment
Line Comment-->

few more
</Node_B>

</Node_A>

我使用过这样的脚本 -

#!/usr/bin/perl 

use strict;
use warnings;
use XML::Twig;
my $infile = 'demo.xml';
my $twig = XML::Twig->new (comments => 'drop', pretty_print => 'indented')->parsefile($infile);
$twig->print ();

该脚本正在删除两条评论中的“CDATA”部分,这不是我的意图。输出如下-

<?xml version="1.0" encoding="UTF-8"?>
<Node_A>
node A content 1

<![CDATA[
this portion is fine]]><Node_B> node B content
<Node_C> node c content
</Node_C>

some data one

some data again two 


few more
</Node_B></Node_A>

我必须添加什么来保持所有 CDATA 部分和其他内容不变,只是为了删除评论?

提前致谢。

4

1 回答 1

4

当我使用您发布的 demo.xml 文件运行您的脚本时,我得到了输出:

<?xml version="1.0" encoding="UTF-8"?>
<Node_A>
node A content 1

<![CDATA[this portion within the two comments is being
REMOVED which is not the intention]]>

node A content 3

<![CDATA[this portion within the two comments is being
REMOVED which is not the intention]]><![CDATA[
this portion is fine]]><Node_B> node B content
<Node_C> node c content
</Node_C>

some data one

some data again two


few more
</Node_B></Node_A>

这对我来说看起来不错。我怀疑你有一个错误版本的XML::Twig(或XML::Parser,它取决于)。我正在使用 Perl 5.14.2、XML::Twig 3.35 和 XML::Parser 2.41。

于 2011-11-15T06:17:40.397 回答