perl如何在写xml文件的时候设定节点的命令
#!/usr/bin/perl
use XML::Simple;
use Data::Dumper;
use Cwd;
my $pwd = cwd();
my $xmlfile = "$pwd/param.xml";
print "-------------------------------\n";
# create array
my @arr = [
{"name"=>"test1","value"=>"/path/to/file/test1"},
{"name"=>"test2","value"=>"test2.txt","check"=>"0"},
{"name"=>"test3","value"=>"test3"},
];
# create object
my $xml = new XML::Simple(NoAttr=>1);
# convert Perl array ref into XML document
my $data = $xml->XMLout(\@arr, outputfile=>"$xmlfile");
这样得到的结果是
<opt>
<anon>
<anon>
<name>test1</name>
<value>/path/to/file/test1</value>
</anon>
<anon>
<name>test2</name>
<check>0</check>
<value>test2.txt</value>
</anon>
<anon>
<name>test3</name>
<value>test3</value>
</anon>
</anon>
</opt>
如果我想得到这样的结果,我应该怎么写?
<root>
<item>
<name>test1</name>
<value>/path/to/file/test1</value>
</item>
<item>
<name>test2</name>
<check>0</check>
<value>test2.txt</value>
</item>
<item>
<name>test3</name>
<value>test3</value>
</item>
</root>
改动是
1.把第二行的<anon>跟倒数第二行的</anon>去掉
2.把anon变为item
[解决办法]
1. my $xmlData = {root => {item => \@arr}};
构造hashtable,提供你所需要的标签,这样xmlout就不会用anon了。(解决问题2)
2.
my @arr = (
{"name"=>"test1","value"=>"/path/to/file/test1"},
{"name"=>"test2","value"=>"test2.txt","check"=>"0"},
{"name"=>"test3","value"=>"test3"},
);
用array而不是list,否则xmlout会用anon把所有的元素用anon包起来。(解决问题1)
#!/usr/bin/perl
use XML::Simple;
use Data::Dumper;
use Cwd;
my $pwd = cwd();
my $xmlfile = "$pwd/param.xml";
print "-------------------------------\n";
# create array
my @arr = (
{"name"=>"test1","value"=>"/path/to/file/test1"},
{"name"=>"test2","value"=>"test2.txt","check"=>"0"},
{"name"=>"test3","value"=>"test3"},
);
my $xmlData = {root => {item => \@arr}};
# create object
my $xml = new XML::Simple(NoAttr=>1, KeepRoot=>1);
# convert Perl array ref into XML document
my $data = $xml->XMLout($xmlData, outputfile=>"$xmlfile");