Reputation: 347
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?
Upvotes: 1
Views: 224
Reputation: 241738
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";
Upvotes: 2
Reputation: 8388
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;
Upvotes: 2
Reputation: 8332
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'
];
Upvotes: 3
Reputation: 1888
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.
Upvotes: -2