in reply to Basic parsing XML perl - using FOREACH

Hello,

You really must use strict; and use warnings; in your programs, otherwise you are rejecting Perl's built-in safety features, and there's not much point in helping when a programmer is doing that.

I believe you are looking for the ForceArray option:

#!/usr/bin/perl use strict; use warnings; use XML::Simple qw/ XMLin /; use Data::Dumper; $Data::Dumper::Sortkeys = 1; local $/; my $staff = XMLin( <DATA>, ForceArray => 1 ); foreach my $employee ( @{ $staff->{'employee'} } ) { print Dumper( $employee ); } __DATA__ <?xml version='1.0'?> <staff> <employee> <name>Pradeep</name> <age>23</age> <sex>M</sex> <department>Coder</department> </employee> <employee> <name>Pradeep</name> <age>22</age> <sex>M</sex> <department>HR</department> </employee> </staff>
Output:
$VAR1 = { 'age' => [ '23' ], 'department' => [ 'Coder' ], 'name' => [ 'Pradeep' ], 'sex' => [ 'M' ] }; $VAR1 = { 'age' => [ '22' ], 'department' => [ 'HR' ], 'name' => [ 'Pradeep' ], 'sex' => [ 'M' ] };
( Note that many monks recommend using XML::Twig or XML::LibXML instead, see the documentation to XML::Simple itself. )

Hope this helps!


The way forward always starts with a minimal test.

Replies are listed 'Best First'.
Re^2: Basic parsing XML perl - using FOREACH
by gr.d (Novice) on Dec 30, 2015 at 07:09 UTC

    Thank you, I have another question though

    what if

    <employee="risc_30"> <name>Pradeep</name> <age>23</age> <sex>M</sex> <department>Coder</department> </employee> <employee="risc_31"> <name>Pradeep</name> <age>22</age> <sex>M</sex> <department>HR</department> </employee>

    how does the foreach loop work then

      That's not valid XML, so the parser will bork.


      The way forward always starts with a minimal test.
Re^2: Basic parsing XML perl - using FOREACH ( warnings; )
by Anonymous Monk on Apr 08, 2016 at 03:16 UTC

    when you say "you must use strict; and use warnings; "

    you must enumerate the problems in OPs code that would be caught by use strict; use warnings;