首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更新XML文件中的值

更新XML文件中的值
EN

Stack Overflow用户
提问于 2012-06-22 19:04:33
回答 2查看 112关注 0票数 0

我有以下格式的XML文件:

代码语言:javascript
复制
<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>

我需要使用Fees1、Fees2、Fees3等更新${Fees}变量。有超过365条记录。有人能告诉我如何通过Perl或Python做到这一点吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-06-22 20:08:16

使用regex进行xml操作并不是一个好主意,但在本例中,我无论如何都会使用它:

Perl脚本:

代码语言:javascript
复制
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>

输出:

代码语言:javascript
复制
<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>

查看并测试它here

如果您想用$Fees变量的实际值替换${Fees},并更改此变量的名称,则使用:

Perl脚本:

代码语言:javascript
复制
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>

输出:

代码语言:javascript
复制
<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>

查看并测试它here

票数 0
EN

Stack Overflow用户

发布于 2012-06-22 20:30:03

简短的Python版本。效率很低,但运行速度很快,超过365个条目。

代码语言:javascript
复制
xml = open("INPUT.XML","rb").read()
count = 1
while "${Fees}" in xml:
    xml = xml.replace("${Fees}", "Fees%d"%count, 1)
    count += 1
open("OUTPUT.XML","wb").write(xml)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11154986

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档