在XML标记之间查找和替换字符

时间:2012-04-17 12:45:22

标签: xml perl

我有一个不受行绑定的XML文件。它有标签<tag1></tag1>,它们从生成它的代码中有一些已删除的变量(我现在无法纠正它)。我希望能够更改这些标签中的字符来纠正它们。角色有时很特别。

我有这个Perl单行显示标签之间的内容,但现在我希望能够在文件中替换它找到的内容。

perl -0777 -ne 'while (/(?<=perform_cnt).*?(?=\<\/perform_cnt)/s) {print $& . "\n";      s/perform_cnt.*?\<\/perform_cnt//s}' output_error.txt

这是XML的一个例子。请注意标记perform_cnt之间的垃圾字符。

<text1>120105728</text1><perform_cnt>ÈPm=</perform_cnt>
<text1>120106394</text1><perform_cnt>†AQ;4K\_Ô23{YYÔ@Nx</perform_cnt>

我需要像0一样替换它们。

2 个答案:

答案 0 :(得分:8)

我喜欢XML::Twig这些事情。它需要一点点习惯,但是一旦你理解了设计(以及一些关于DOM处理的东西),许多事情变得非常容易:

use XML::Twig;

my $xml = <<'HERE';
<root>
<text1>120105728</text1><perform_cnt>ÈPm=</perform_cnt>
<text1>120106394</text1><perform_cnt>†AQ;4K\_Ô23{YYÔ@Nx</perform_cnt>
</root>
HERE

my $twig = XML::Twig->new(   
    twig_handlers => { 
        perform_cnt   => sub { 
            say "Text is " => $_->text;  # get the current text

            $_->set_text( 'Buster' );    # set the new text
            },
      },
    pretty_print => 'indented',
    );

$twig->parse( $xml );
$twig->flush; 

通过缩进的漂亮打印,我得到:

<root>
  <text1>120105728</text1>
  <perform_cnt>Buster</perform_cnt>
  <text1>120106394</text1>
  <perform_cnt>Buster</perform_cnt>
</root>

答案 1 :(得分:0)

使用正则表达式进行xml解析

是一种不好的做法

无论如何 - 代码是:

#!/usr/bin/perl

use strict;
use warnings;

my $tag = 'perform_cnt';

open my $fh, '<file.txt' or die $!;
foreach (<$fh>) {
  s/(<$tag>)(.*?)(<\/$tag>)/$1$3/g;
  print "$_";
}
close $fh;

输出是:

<text1>120105728</text1><perform_cnt></perform_cnt>
<text1>120106394</text1><perform_cnt></perform_cnt>
相关问题