What is the easiest way to do an XPath query for XML data in Perl?

I'm looking for the easiest way to quickly get data from an XML structure using XPath queries in Perl.

The following code structure explains what I would 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'); 

TIMTOWTDI is obviously applied, but what would be the easiest way to do this?

+4
source share
2 answers

XML :: LibXML is no simpler, but superior to XML :: XPath in any other way.

 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; 
+14
source
 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 } 
+6
source

Source: https://habr.com/ru/post/1343348/


All Articles