1#!/usr/bin/perl -w
2use strict;
3
4$| = 1;
5
6unless (@ARGV >= 1) {
7	print STDERR qq(Usage:
8$0 [filename] query
9				
10	If no filename is given, supply XML on STDIN.
11);
12	exit;
13}
14
15use XML::XPath;
16
17my $xpath;
18
19my $pipeline;
20
21if ($ARGV[0] eq '-p') {
22	# pipeline mode
23	$pipeline = 1;
24	shift @ARGV;
25}
26if (@ARGV >= 2) {
27	$xpath = XML::XPath->new(filename => shift(@ARGV));
28}
29else {
30	$xpath = XML::XPath->new(ioref => \*STDIN);
31}
32
33my $nodes = $xpath->find(shift @ARGV);
34
35unless ($nodes->isa('XML::XPath::NodeSet')) {
36NOTNODES:
37	print STDERR "Query didn't return a nodeset. Value: ";
38	print $nodes->value, "\n";
39	exit;
40}
41
42if ($pipeline) {
43	$nodes = find_more($nodes);
44	goto NOTNODES unless $nodes->isa('XML::XPath::NodeSet');
45}
46
47if ($nodes->size) {
48	print STDERR "Found ", $nodes->size, " nodes:\n";
49	foreach my $node ($nodes->get_nodelist) {
50		print STDERR "-- NODE --\n";
51		print $node->toString;
52	}
53}
54else {
55	print STDERR "No nodes found";
56}
57
58print STDERR "\n";
59
60exit;
61
62sub find_more {
63	my ($nodes) = @_;
64	if (!@ARGV) {
65		return $nodes;
66	}
67	
68	my $newnodes = XML::XPath::NodeSet->new;
69	
70	my $find = shift @ARGV;
71	
72	foreach my $node ($nodes->get_nodelist) {
73		my $new = $xpath->find($find, $node);
74		if ($new->isa('XML::XPath::NodeSet')) {
75			$newnodes->append($new);
76		}
77		else {
78			warn "Not a nodeset: ", $new->value, "\n";
79		}
80	}
81	
82	return find_more($newnodes);
83}
84