使用 perl 脚本在 XML 文件中用字符串替换数字

问题描述

我有一个 XML 文件。我需要用 comment="my string" 替换 comment="18" 中的数字,其中我的字符串来自我的 @array ($array[18] = my string)。

 <rule ccType="inst" comment="18" domain="icc" entityName="thens"  entityType="toggle" excTime="1605163966" name="exclude" reviewer="hpanjali" user="1" vscope="default"></rule>

这是我试过的。

while (my $line = <FH>) {
      chomp $line;
      $line =~ s/comment="(\d+)"/comment="$values[$1]"/ig;
    #  print "$line \n";
      print FH1 $line,"\n";

}

解决方法

这是一个使用 XML::LibXML 的例子:

use strict;
use warnings;
use XML::LibXML;

my $fn = 'test.xml';
my @array = map { "string$_" } 0..20;
my $doc = XML::LibXML->load_xml(location => $fn);
for my $node ($doc->findnodes('//rule')) {
    my $idx = $node->getAttribute('comment');
    $node->setAttribute('comment',$array[$idx]);
}
print $doc->toString();
,

这是一个 XML::Twig 示例。这与使用不同工具以不同方式完成的 XML::LibXML example 基本相同:

use XML::Twig;

my $xml =
qq(<rule ccType="inst" comment="18"></rule>);

my @array;
$array[18] = 'my string';

my $twig = XML::Twig->new(
    twig_handlers => {
        rule => \&update_comment,},);
$twig->parse( $xml );
$twig->print;

sub update_comment {
    my( $t,$e ) = @_;
    my $n = $e->{att}{comment};
    $e->set_att( comment => $array[$n] );
    }

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...