问题描述
我有一个 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] );
}