如何从XML :: Simple访问嵌套数据结构中的数据?

时间:2012-06-26 00:13:52

标签: xml perl data-structures reference xml-simple

我必须编写一个Perl脚本来将XML文件转换为CSV文件。我已经在一个上下文中编写了一些简单的东西,并且需要针对不同的数据集进行增强,并且无法确定要做什么。

我正在使用XML::Simple

以下是数据的一条记录:

<custom-objects xmlns="http://www.demandware.com/xml/impex/customobject/2006-10-31">
    <custom-object type-id="emailBackInStockHistory" object-id="bczCAiaag0APcaaacLsvpJRmzW">
        <object-attribute attribute-id="email">some@email.com</object-attribute>
        <object-attribute attribute-id="emailSentAt">2010-04-10T09:00:01.000+0000</object-attribute>
        <object-attribute attribute-id="productID">someprodid</object-attribute>
        <object-attribute attribute-id="requestedAt">2010-04-09T10:07:54.000+0000</object-attribute>
        <object-attribute attribute-id="siteID">someSITEid</object-attribute>
    </custom-object>
</custom-objects>

使用Data::Dumper模块,我看到数据被解析为:

'custom-object' => [
    {
        'type-id'          => 'emailBackInStockHistory',
        'object-id'        => 'bczCAiaag0APcaaacLsvpJRmzW',
        'object-attribute' => [
            {
                'attribute-id' => 'email',
                'content'      => 'some@email.com'
            },
            {
                'attribute-id' => 'emailSentAt',
                'content'      => '2010-04-10T09:00:01.000+0000'
            },
            {
                'attribute-id' => 'productID',
                'content'      => 'someprodid'
            },
            {
                'attribute-id' => 'requestedAt',
                'content'      => '2010-04-09T10:07:54.000+0000'
            },
            {
                'attribute-id' => 'siteID',
                'content'      => 'someSITEid'
            }
        ]
    },

以下是我尝试用来执行此导出的一些代码:

foreach $o (@{$data->{'custom-object'}}) {
    print $o->{'type-id'},   ",";
    print $o->{'object-id'}, ",";
    print $o->{'custom-object'}->{'object-attribute'}->{'email'}, ",";
    print "\n";

type-idobject-id属性输出正确,但我无法弄清楚如何从object-attribute引用中打印数据。

1 个答案:

答案 0 :(得分:2)

您需要像使用object-attribute array-ref一样迭代custom-object数组引用。另请查看Text::CSV以获得更强大的创建csv文件的方法。

foreach my $obj ( @{ $data->{'custom-object'} } ) {
    print $obj->{'type-id'}, ",";
    print $obj->{'object-id'}, ",";
    foreach my $attr ( @{ $obj->{'object-attribute'} } ) {
        if ( $attr->{'attribute-id'} eq 'email' ) {
            print $attr->{'content'}, ",";
        }
    }
    print "\n";
}