问题
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?
回答1:
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;
回答2:
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
}
来源:https://stackoverflow.com/questions/5275610/what-is-the-easiest-way-to-do-xpath-querying-of-xml-data-in-perl