我正在尝试使用XML :: Simple CPAN模块将我们数据库的输出转换为简单的XML结构。问题是,无论我尝试传递给XML :: Simple的选项,返回的输出都不是我所希望的。
我们尝试输出的数据库表只是一堆带有定义的项目:
CREATE TABLE `items` (
`id` int(8) NOT NULL,
`name` varchar(40) NOT NULL,
`manufacturer` varchar(40) NOT NULL,
`added` datetime NOT NULL,
PRIMARY KEY (`id`)
);
以下是我们目前使用的Perl代码:
my $SQL = qq| select * from items |;
my $sth = main::DatabaseQuery($SQL);
my $items;
my $count = 0;
while(my $item = $sth->fetchrow_hashref()) {
$items->[$count] = $item;
$count++;
}
require XML::Simple;
my $xs = XML::Simple->new(ForceArray => 1, KeepRoot => 1);
my $xml = $xs->XMLout($ref);
这将输出以下XML:
<anon id="10000" name="Item 1" manufacturer="Manufacturer 1" added="2009-01-01" />
<anon id="10001" name="Item 2" manufacturer="Manufacturer 2" added="2009-01-01" />
<anon id="10002" name="Item 3" manufacturer="Manufacturer 3" added="2009-01-01" />
我想要输出如下:
<items>
<item>
<id>10000</id>
<name>Item 1</name>
<manufacturer>Manufacturer 1</manufacturer>
<added>2009-01-01</added>
</item>
<item>
<id>10001</id>
<name>Item 2</name>
<manufacturer>Manufacturer 2</manufacturer>
<added>2009-01-01</added>
</item>
<item>
<id>10002</id>
<name>Item 3</name>
<manufacturer>Manufacturer 3</manufacturer>
<added>2009-01-01</added>
</item>
</items>
我确信我有一些小问题,所以请让我知道如何更改当前的实现以生成所需的XML输出。提前谢谢!
答案 0 :(得分:6)
尝试:
my $SQL = qq| select * from items |;
my $sth = main::DatabaseQuery($SQL);
my $items = [];
while(my $item = $sth->fetchrow_hashref()) {
push @$items, $item;
}
use XML::Simple;
my $xs = XML::Simple->new(ForceArray => 1, KeepRoot => 1, NoAttr => 1);
my $xml = $xs->XMLout( { items => { item => $items } } );
请注意,我将其更改为使用push而不是计数并分配到最后一个数组索引以及初始化项目,这样在没有数据行时就不会得到<item></item>
。