Search code examples
xmlperlxpathcpan

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


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?


Solution

  • 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;