1

I am new to the Perl language. I have an XML like,

<xml>
   <date>
       <date1>2012-10-22</date1>
       <date2>2012-10-23</date2>
   </date>
</xml>

I want to parse this XML file & store it in array. How to do this using perl script?

3

4 Answers 4

3
Use XML::Simple - Easy API to maintain XML (esp config files) or 
see XML::Twig - A perl module for processing huge XML documents in tree mode.

Example like:

use strict;
use warnings;
use XML::Simple;
use Data::Dumper;

my $xml = q~<xml>
   <date>
       <date1>2012-10-22</date1>
       <date2>2012-10-23</date2>
   </date>
</xml>~;

print $xml,$/;

my $data = XMLin($xml);

print Dumper( $data );

my @dates;
foreach my $attributes (keys %{$data->{date}}){
  push(@dates, $data->{date}{$attributes})
}

print Dumper(\@dates);

Output:

$VAR1 = [
          '2012-10-23',
          '2012-10-22'
        ];
Sign up to request clarification or add additional context in comments.

Comments

2

Here's one way with XML::LibXML

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

my $doc = XML::LibXML->load_xml(location => 'data.xml');
my @nodes = $doc->findnodes('/xml/date/*');
my @dates = map { $_->textContent } @nodes;

Comments

2

Using XML::XSH2, a wrapper around XML::LibXML:

#!/usr/bin/perl
use warnings;
use strict;

use XML::XSH2;

xsh << '__XSH__';
  open 2.xml ;
  for $t in /xml/date/* { 
      my $s = string($t) ;
      perl { push @l, $s }
  }
__XSH__

no warnings qw(once);
print join(' ', @XML::XSH2::Map::l), ".\n";

Comments

-2

If you can't/don't want to use any CPAN mod:

my @hits= $xml=~/<date\d+>(.+?)<\/date\d+>/

This should give you all the dates in the @hits array.

If the XML isn't as simple as your example, using a XML parser is recommended, the XML::Parser is one of them.

3 Comments

never use regex for parsing xml
well that's assuming you CAN use another tool, but I've found myself working in very old servers where I could not use them, so if the XML is simple enough using a regex is not pretty but works.
If you can run Perl code that you write, you can use a Pure Perl XML library.

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.