This is my XML format:
<A>
<B>
<C>..</C>
<D>..</D>
<E>..</E>
</B>
</A>
And here's my code :
use strict;
use warnings;
use Data::Dumper;
use XML::Simple;
open(my $fh, '<', '/tmp/abc.xml');
my $xml = new XML::Simple;
my $data = $xml->XMLin($fh) or die "Failed to find $fh";
my $value = $data->{'B'};
print $value->{'C'}
Giving error:
Not a HASH reference.
Can you please explain where I'm going wrong?
You're going wrong in a couple of ways: First, using an obsolete module for XML parsing whose documentation is full of warnings to not use it, and not using an XPath expression to get at the data you want. The following uses XML::LibXML
instead:
#!/usr/bin/env perl
use warnings;
use strict;
use feature qw/say/;
use XML::LibXML;
my $xml = XML::LibXML->load_xml(IO => \*DATA);
# my $xml = XML::LibXML->load_xml(location => '/tmp/abc.xml');
my @nodes = $xml->findnodes('/A/B/C');
for my $node (@nodes) {
say $node->textContent();
}
__DATA__
<A>
<B>
<C>..</C>
<D>..</D>
<E>..</E>
</B>
</A>
Or using XML::Twig
instead:
#!/usr/bin/env perl
use warnings;
use strict;
use feature qw/say/;
use XML::Twig;
my $twig =
XML::Twig->new(twig_handlers => { '/A/B/C' => sub { say $_[1]->text } });
$twig->parse(\*DATA);
# $twig->parsefile('/tmp/abc.xml');
__DATA__
<A>
<B>
<C>..</C>
<D>..</D>
<E>..</E>
</B>
</A>