如何使用Twig模块从XML中删除注释

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部分和其他内容,只是要删除注释?

提前感谢。

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。


同样的情况,代码运行良好。我怀疑这不是任何一个模块的错误,据我所知,处理注释的代码已经多年没有更改过了。 - mirod
你说得完全正确。我的 Twig 版本相当老旧(3.13),现在安装了当前版本后它按预期运行。 - Soumava Roy
请问一下,这个脚本是否会受到 XML 文件大小的影响?实际上,对于超过 1000 行的大型 XML 文件,这个脚本能否成功删除注释? - Soumava Roy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接