0

I'm using perl with XML::Simple to print the contents of a XML file. The structure of the XML file however prevents me from listing all entries since I cannot find the right way to loop over the nested arrays. Can anyone help me out and show how to do this?

The XML structure is like:

<header>
 <rows>
  <row>
   <elem>a</elem>
   <elem>b</elem>
   <elem>c</elem>
  </row>
  <row>
   <elem>d</elem>
   <elem>e</elem>
   <elem>f</elem>
  </row>
 </rows>
</header>

My program is like this:

 my $infile = test.xml;
 my $xml = new XML::Simple (KeyAttr=>[]);
 my $main = $xml->XMLin("$infile",SuppressEmpty => '');

I can print separate entries of elem using

 print "$main->{rows}->{row}->[0]->{elem}[0]\n";

and print all entries of the n-th elem using

 for (@{$main->{rows}{row}}) {
    print "$_->{elem}[0] \n";
 }

This would print

 a
 d

But how do I print this:

 a;b;c;
 d;e;f;

Thanks for any answers.

2 Answers2

2

I would start with "don't use XML::Simple" - I quite like XML::Twig as a nice and easy to use alternative. (XML::LibXML is good too, but has a bit more of a learning curve):

#!/usr/bin/env perl
use strict;
use warnings;
use XML::Twig;

my $xml = XML::Twig -> parsefile ( $infile );

foreach my $row ( $xml -> get_xpath('//row') ) {
   print join ( ";", map { $_ -> text } $row -> children('elem')),"\n";
}

Prints:

a;b;c
d;e;f

(Unrolling the loops for the sake of clarity:

foreach my $row ( $xml -> get_xpath('//row') ) {
   foreach my $elem ( $row -> children ( 'elem' ) ) { 
      print $elem -> text, ";";
   }
   print "\n";
}
Community
  • 1
  • 1
Sobrique
  • 52,974
  • 7
  • 60
  • 101
0
print join ';', @{ $_->{elem} }, "\n";
ysth
  • 96,171
  • 6
  • 121
  • 214