2

I've created the below XML file for retrieving data.

Input:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<ExecutionLogs>
    <category cname='Condition1' cid='T1'>
        <log>value1</log>
        <log>value2</log>
        <log>value3</log>
    </category>
    <category cname='Condition2' cid='T2'>
        <log>value4</log>
        <log>value5</log>
        <log>value6</log>
    </category>
        <category cname='Condition3' cid='T3'>
        <log>value7</log>
    </category>
</ExecutionLogs>

I want the output like below,

Condition1 -> value1,value2,value3
Condition2 -> value4,value5,value6
Condition3 -> value7

I have tried the code below,

use strict;
use XML::Simple;
my $filename = "input.xml";
$config = XML::Simple->new();
$config = XMLin($filename);
@values = @{$config->{'category'}{'log'}};

Please help me on this. Thanks in advance.

Vasanth
  • 365
  • 2
  • 13

2 Answers2

4

A way to do this using XML::Twig:

#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

XML::Twig->new( twig_handlers => { 
                   category => sub { print $_->att( 'cname'), ': ', 
                                           join( ',', $_->children_text( 'log')), "\n";
                               },
                },
              )

         ->parsefile( 'my.xml');

The handler is called each time a category element has been parsed. $_ is the element itself.

mirod
  • 15,923
  • 3
  • 45
  • 65
1

What I would do :

use strict; use warnings;
use XML::Simple;
my $config = XML::Simple->new();
$config = XMLin($filename, ForceArray => [ 'log' ]);
#   we want an array here  ^---------------------^ 

my @category = @{ $config->{'category'} };
#              ^------------------------^
# de-reference of an ARRAY ref  

foreach my $hash (@category) {
    print $hash->{cname}, ' -> ', join(",", @{ $hash->{log} }), "\n";
}

OUTPUT

Condition1 -> value1,value2,value3
Condition2 -> value4,value5,value6
Condition3 -> value7

NOTE

ForceArray => [ 'log' ] is there to ensure treating same types in {category}->[@]->{log] unless that, we try to dereferencing an ARRAY ref on a string for the last "Condition3".

Check XML::Simple#ForceArray

and

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223