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?
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
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With