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.

1
  • 1
    You should describe the problem you are facing Commented Dec 16, 2014 at 5:59

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.