Example
# This uses the 'sample.xml' given in the XML::Twig example.
# Module requirements (1.70 and above for use of load_xml)
use XML::LibXML '1.70';
# let's be a good perl dev
use strict;
use warnings 'all';
# Create the LibXML Document Object
my $xml = XML::LibXML->new();
# Where we are retrieving the XML from
my $file = 'sample.xml';
# Load the XML from the file
my $dom = XML::LibXML->load_xml(
location => $file
);
# get the docroot
my $root = $dom->getDocumentElement;
# if the document has children
if($root->hasChildNodes) {
# getElementsByLocalName returns a node list of all elements who's
# localname matches 'title', and we want the first occurrence
# (via get_node(1))
my $title = $root->getElementsByLocalName('title');
if(defined $title) {
# Get the first matched node out of the nodeList
my $node = $title->get_node(1);
# Get the text of the target node
my $title_text = $node->textContent;
print "The first node with name 'title' contains: $title_text\n";
}
# The above calls can be combined, but is possibly prone to errors
# (if the getElementsByLocalName() failed to match a node).
#
# my $title_text = $root->getElementsByLocalName('title')->get_node(1)->textContent;
}
# Using Xpath, get the price of the book with id 'bk104'
#
# Set our xpath
my $xpath = q!/catalog/book[@id='bk104']/price!;
# Does that xpath exist?
if($root->exists($xpath)) {
# Pull in the twig
my $match = $root->find($xpath);
if(defined $match) {
# Get the first matched node out of the nodeList
my $node = $match->get_node(1);
# pull in the text of that node
my $match_text = $node->textContent;
print "The price of the book with id bk104 is: $match_text\n";
}
}