Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl, how to parse XML file, xpath

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 :-)

like image 569
liverpaul Avatar asked Mar 11 '12 00:03

liverpaul


People also ask

How do I read an XML file in Perl?

If you have the XML in a string, instead of location , use string : $dom = XML::LibXML->load_xml(string => $xml_string); Or, you can provide a Perl file handle to parse from an open file or socket, using IO : $dom = XML::LibXML->load_xml(IO => $fh);

What is XPath expression in XML?

XPath uses path expressions to select nodes or node-sets in an XML document. These path expressions look very much like the expressions you see when you work with a traditional computer file system. XPath expressions can be used in JavaScript, Java, XML Schema, PHP, Python, C and C++, and lots of other languages.

What is XPath parsing?

It defines a language to find information in an XML file. It is used to traverse elements and attributes of an XML document. XPath provides various types of expressions which can be used to enquire relevant information from the XML document.


1 Answers

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.

like image 71
daxim Avatar answered Oct 23 '22 19:10

daxim