在 Perl 中,如何在不更改 XML 文件格式的情况下更改 XML 文件中的元素? [英] In Perl, how can I change an element in an XML file without changing the format of the XML file?
问题描述
我有一个格式如下的 XML 文件:
I have a XML file of the format:
<outer1>
<inner1>
<name>Stonecold</name>
<profession>warrior</profession>
<org>wwf</org>
</inner1>
<inner1>
<name>Shanebond</name>
<profession>Bowler</profession>
<org>newzealand</org>
</inner1>
<inner1>
<name>brain schemidit</name>
<profession>Chairman</profession>
<org>Google</org>
</inner1>
</outer1>
我想把Shanebond
的值改成Shane Bond
.
我使用的是 XML::Simple
,但结果是一个哈希值.
I was using XML::Simple
, but the result was a hash.
我想要与输入文件相同的格式.例如:输出文件应如下所示:
I want the same format as the input file. E.g: the output file should be as follows:
<outer1>
<inner1>
<name>Stonecold</name>
<profession>warrior</profession>
<org>wwf</org>
</inner1>
<inner1>
<name>Shane Bond</name>
<profession>Bowler</profession>
<org>newzealand</org>
</inner1>
<inner1>
<name>brain schemidit</name>
<profession>Chairman</profession>
<org>Google</org>
</inner1>
</outer1>
请建议如何做到这一点.
Please advice how to do this.
提前致谢.
我希望将输出文件保存在同一目录中,并尽可能使用相同的名称.有可能吗?
I want the output file to be saved in the same directory and if possible with the same name. is it possible?
推荐答案
XML::Simple
有一些选项允许您指定输入将如何转换为 Perl 数据结构以及该结构将如何输出:
XML::Simple
has options that allow you to specify how input will be transformed into a Perl data structure and how that structure will be output:
#!/usr/bin/perl
use strict;
use warnings;
use XML::Simple;
my $xml_file = 'b.xml';
my $xml = XMLin(
$xml_file,
KeepRoot => 1,
ForceArray => 1,
);
$xml->{outer1}->[0]->{inner1}->[1]->{name} = 'Shane Bond';
XMLout(
$xml,
KeepRoot => 1,
NoAttr => 1,
OutputFile => $xml_file,
);
XML::Simple
确实有点麻烦,如果你可以做任何有趣的事情,因为它的目的不是成为一个通用的 XML 库,而是提供一种处理用 XML 编写的配置文件的简单方法.
XML::Simple
does get a little hairy if you do anything interesting because its purpose is not to be a general purpose XML library but to provide a simple way to deal with configuration files written in XML.
CPAN 有大量XML 相关模块.除非这是您必须处理的一次性问题,否则值得研究一些功能更强大、更适合的模块.
CPAN has a plethora of XML related modules. Unless this was a one-off issue you had to deal with, it would be worth looking into some of the more capable and better suited modules.
这篇关于在 Perl 中,如何在不更改 XML 文件格式的情况下更改 XML 文件中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!