#!/usr/bin/perl
#
# For testing various XPath queries - http://sial.org/howto/xml/
#
# $Id$
use strict;
use warnings;
use XML::LibXML ();
use XML::LibXML::XPathContext ();
########################################################################
#
# MAIN
my ( $xml_file, $xpath_query, $context_query ) = @ARGV;
if ( !defined $xml_file or !defined $xpath_query ) {
die "Usage: $0 xml-file xpath-query xpath-context-query\n";
}
$context_query = '/' unless defined $context_query;
my $doc = XML::LibXML->new()->parse_file($xml_file);
my $xc = XML::LibXML::XPathContext->new($doc);
# for undec.xml xmlns support:
$xc->registerNs( 'u', 'http://example.org/undec/1.0/' );
my $context_node = $xc->findnodes($context_query)->get_node(1);
if ( !defined $context_node ) {
die "error: no result from context query: $context_query\n";
}
print handle_result( $xc->find( $xpath_query, $context_node ) ), "\n";
exit 0;
########################################################################
#
# SUBROUTINES
sub handle_result {
my $result = shift;
die "error: no result" if !defined $result;
my $output;
if ( $result->can('to_literal') ) {
$output = $result->to_literal;
} elsif ( $result->isa('XML::LibXML::Literal') ) {
$output = $result->value;
} else {
die "error: do not know how to handle: ", ref $result, "\n";
}
return $output;
}