Alex Rivera | Logout

Perl, how to parse XML file, xpath

Asked 2012-03-11T00:04:16.750
12

I want to parse an XML file using Perl. I was able to do it using the XML::Simple module, but now I want to start using the XML::XPath module instead because it uses XPath expressions. From my limited knowledge I think XPaths will make future parsing easier, right? Here's the Perl code I have so far:

use strict;
use warnings;
use XML::XPath;

my $file = "data.xml";
my $path = XML::XPath->new(filename => $file);

my $name = $path->find('/category/event/@name');
print $name."\n";

My question is how do I separate each name attribute (category/event/@name) so that I can perform tests on each value I parse. At the moment I'm just getting a big string full of the parsed data, whereas I want several small strings that I can test. How can I do this? Thanks :-)

Edit
Report

1 Answer

20

This review points out that XML::XPath hasn't been updated since 2003, and recommends XML::LibXML instead

use 5.010;
use strict;
use warnings;
use XML::LibXML;

my $dom = XML::LibXML->new->parse_file('data.xml');
for my $node ($dom->findnodes('/category/event/@name')) {
    say $node->toString;
}

See XML::LibXML::Parser and XML::LibXML::Node.

answered 2012-03-11T01:23:13.687

Your Answer