使用正则表达式进行 xml 操作并不是一个好主意,但在这种情况下,我还是会使用它:
Perl 脚本:
my $xml = join (/\n/, <main::DATA>);
my @fees = (1, 2, 3, 4);
$xml =~ s/(<Status Fees=")\${Fees}("\/>)/{$1 . shift(@fees) . $2}/ige;
print "$xml";
__DATA__
<Principal ID="122" >
<Status Fees="${Fees}"/>
</Principal>
<Principal ID="123" >
<Status Fees="${Fees}"/>
</Principal>
<Principal ID="124" >
<Status Fees="${Fees}"/>
</Principal>
<Principal ID="125" >
<Status Fees="${Fees}"/>
</Principal>
输出:
<Principal ID="122" >
<Status Fees="1"/>
</Principal>
<Principal ID="123" >
<Status Fees="2"/>
</Principal>
<Principal ID="124" >
<Status Fees="3"/>
</Principal>
<Principal ID="125" >
<Status Fees="4"/>
</Principal>
在这里查看并测试它。
如果要替换${Fees}
为变量的实际值$Fees
并且此变量的名称发生更改,请使用:
Perl 脚本:
my $xml = join (/\n/, <main::DATA>);
my ($fee1, $fee2, $fee3, $fee4) = (1, 2, 3, 4);
$xml =~ s/(<Status Fees=")\${(.*?)}("\/>)/{$1 . eval('$'.$2) . $3}/ige;
print "$xml";
__DATA__
<Principal ID="122" >
<Status Fees="${fee1}"/>
</Principal>
<Principal ID="123" >
<Status Fees="${fee2}"/>
</Principal>
<Principal ID="124" >
<Status Fees="${fee3}"/>
</Principal>
<Principal ID="125" >
<Status Fees="${fee4}"/>
</Principal>
输出:
<Principal ID="122" >
<Status Fees="1"/>
</Principal>
<Principal ID="123" >
<Status Fees="2"/>
</Principal>
<Principal ID="124" >
<Status Fees="3"/>
</Principal>
<Principal ID="125" >
<Status Fees="4"/>
</Principal>
在这里查看并测试它。