Regex 使用perl脚本将XML文件中的数字替换为字符串

Regex 使用perl脚本将XML文件中的数字替换为字符串,regex,xml,perl,Regex,Xml,Perl,我有一个XML文件。我需要用comment=“my string”替换comment=“18”中的数字,其中我的字符串来自我的@array($array[18]=我的字符串) 这就是我尝试过的 while (my $line = <FH>) { chomp $line; $line =~ s/comment="(\d+)"/comment="$values[$1]"/ig; # print "$l

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


这就是我尝试过的

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

}
while(我的$line=){
chomp$行;
$line=~s/comment=“(\d+)”/comment=“$values[$1]”/ig;
#打印“$line\n”;
打印FH1$行“\n”;
}
以下是一个示例:

这里有一个例子。这与使用不同的工具以不同的方式完成的任务基本相同:

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] );
    }
使用XML::Twig;
我的$xml=
qq();
我的@数组;
$array[18]=“我的字符串”;
my$twig=XML::twig->new(
细枝处理程序=>{
规则=>\&更新\注释,
},
);
$twig->parse($xml);
$twig->print;
子更新注释{
我的($t,$e)=@;
my$n=$e->{att}{comment};
$e->set_att(注释=>$array[$n]);
}

您尝试过什么?你有什么问题?请出示您的密码。谢谢。我不是perl方面的专家。我知道简单的perl。我在(我的$line=){chomp$line;$line=~s/comment=“(\d+)”/comment=“$values[$1]”/ig;#print“$line\n”;print FH1$line“\n”}时尝试过这个方法,并且认为可能有一些有效的方法可以使用XMLPerl模块实现这一点,因此我提出了这个问题。非常感谢你的回答。我不是perl方面的专家。我知道简单的perl。我在(我的$line=){chomp$line;$line=~s/comment=“(\d+)”/comment=“$values[$1]”/ig;#print“$line\n”;print FH1$line“\n”}时尝试过这个方法,并且认为可能有一些有效的方法可以使用XMLPerl模块实现这一点,因此我提出了这个问题。非常感谢你的回答。
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();
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] );
    }