Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to do XPath querying of XML data in Perl?

Tags:

xml

perl

xpath

cpan

I am looking for the simplest way possible to quickly retrieve data from an XML structure using XPath queries in Perl.

The following code structure explains what I'd like to achieve:

my $xml_data = "<foo><elementName>data_to_retrieve</elementName></foo>";
my $xpath_query = "//elementName";
my $result_of_query = ... what goes here? ...
die unless ($result_of_query eq 'data_to_retrieve');

Obviously TIMTOWTDI applies, but what would be the easiest way to do it?

like image 284
knorv Avatar asked Nov 30 '22 08:11

knorv


2 Answers

use XML::XPath;
use XML::XPath::XMLParser;

my $xp = XML::XPath->new(xml => $xml_data);

my $result_of_query = $xp->find('//elementName'); # find all nodes that match

foreach my $node ($result_of_query->get_nodelist) {
       #Do someting
}
like image 35
Shamit Verma Avatar answered Dec 06 '22 10:12

Shamit Verma


XML::LibXML is not easier, but beats XML::XPath in every other aspect.

use XML::LibXML;
my $xml_data = XML::LibXML->load_xml(
    string => '<foo><elementName>data_to_retrieve</elementName></foo>'
);
die unless 'data_to_retrieve' eq
    $xml_data
      ->findnodes('//elementName')
      ->get_node(1)
      ->textContent;
like image 107
daxim Avatar answered Dec 06 '22 09:12

daxim