XPath.pm

filter: Statementstmt 86.6% 13 / 15 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 90.0% 18 / 20 CC 1 SCAR 0.6
CC
1
Cov
87%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« XPath/XMLParser.pm ↑ Summary XPath/Parser.pm »
1 package XML::XPath;
2  
3 =head1 NAME
4  
5 XML::XPath - Parse and evaluate XPath statements.
6  
7 =head1 VERSION
8  
9 Version 1.26
10  
11 =cut
12  
13 1 ▶use strict; use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use vars qw($VERSION $AUTOLOAD $revision);
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 $VERSION = '1.26';
17 $XML::XPath::Namespaces = 1;
18 $XML::XPath::Debug = 0;
19  
20 1 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 1 ▶use XML::XPath::XMLParser;
Subroutine BEGIN: called CC=1 SCAR=2.6
22 use XML::XPath::Parser;
23 use IO::File;
24  
25 # Parameters for new()
26 my @options = qw(
27 filename
28 parser
29 xml
30 ioref
31 context
32 );
33  
34 =head1 DESCRIPTION
35  
36 This module aims to comply exactly to the XPath specification at http://www.w3.org/TR/xpath
37 and yet allow extensions to be added in the form of functions.Modules such as XSLT
38 and XPointer may need to do this as they support functionality beyond XPath.
39  
40 =head1 SYNOPSIS
41  
42 use XML::XPath;
43 use XML::XPath::XMLParser;
44  
45 my $xp = XML::XPath->new(filename => 'test.xhtml');
46  
47 my $nodeset = $xp->find('/html/body/p'); # find all paragraphs
48  
49 foreach my $node ($nodeset->get_nodelist) {
50 print "FOUND\n\n",
51 XML::XPath::XMLParser::as_string($node),
52 "\n\n";
53 }
54  
55 =head1 DETAILS
56  
57 There is an awful lot to all of this, so bear with it - if you stick it out it
58 should be worth it. Please get a good understanding of XPath by reading the spec
59 before asking me questions. All of the classes and parts herein are named to be
60 synonymous with the names in the specification, so consult that if you don't
61 understand why I'm doing something in the code.
62  
63 =head1 METHODS
64  
65 The API of XML::XPath itself is extremely simple to allow you to get going almost
66 immediately. The deeper API's are more complex, but you shouldn't have to touch
67 most of that.
68  
69 =head2 new()
70  
71 This constructor follows the often seen named parameter method call. Parameters
72 you can use are: filename, parser, xml, ioref and context. The filename parameter
73 specifies an XML file to parse. The xml parameter specifies a string to parse,
74 and the ioref parameter specifies an ioref to parse. The context option allows
75 you to specify a context node. The context node has to be in the format of a node
76 as specified in L<XML::XPath::XMLParser>. The 4 parameters filename, xml, ioref
77 and context are mutually exclusive - you should only specify one (if you specify
78 anything other than context, the context node is the root of your document). The
79 parser option allows you to pass in an already prepared XML::Parser object, to
80 save you having to create more than one in your application (if, for example, you
81 are doing more than just XPath).
82  
83 my $xp = XML::XPath->new( context => $node );
84  
85 It is very much recommended that you use only 1 XPath object throughout the life
86 of your application. This is because the object (and it's sub-objects) maintain
87 certain bits of state information that will be useful (such as XPath variables)
88 to later calls to find(). It's also a good idea because you'll use less memory
89 this way.
90  
91 =cut
92  
93 sub new {
94 my $proto = shift;
95 my $class = ref($proto) || $proto;
96  
97 my(%args);
98 # Try to figure out what the user passed
99 if ($#_ == 0) { # passed a scalar
100 my $string = $_[0];
101 if ($string =~ m{<.*?>}s) { # it's an XML string
102 $args{'xml'} = $string;
103 } elsif (ref($string)) { # read XML from file handle
104 $args{'ioref'} = $string;
105 } elsif ($string eq '-') { # read XML from stdin
106 $args{'ioref'} = IO::File->new($string);
107 } else { # read XML from a file
108 $args{'filename'} = $string;
109 }
110 } else { # passed a hash or hash reference
111 # just pass the parameters on to the XPath constructor
112 %args = ((ref($_[0]) eq "HASH") ? %{$_[0]} : @_);
113 }
114  
115 if ($args{filename} && (!-e $args{filename} || !-r $args{filename})) {
116 die "Cannot open file '$args{filename}'";
117 }
118  
119 my %hash = map(( "_$_" => $args{$_} ), @options);
120 $hash{path_parser} = XML::XPath::Parser->new();
121 return bless \%hash, $class;
122 }
123  
124 =head2 find($path, [$context])
125  
126 The find function takes an XPath expression (a string) and returns either an XML::XPath::NodeSet
127 object containing the nodes it found (or empty if no nodes matched the path), or
128 one of L<XML::XPath::Literal> (a string), L<XML::XPath::Number> or L<XML::XPath::Boolean>.
129 It should always return something - and you can use ->isa() to find out what it
130 returned. If you need to check how many nodes it found you should check $nodeset->size.
131 See L<XML::XPath::NodeSet>. An optional second parameter of a context node allows
132 you to use this method repeatedly, for example XSLT needs to do this.
133  
134 =cut
135  
136 sub find {
137 my ($self, $path, $context) = @_;
138  
139 die "No path to find" unless $path;
140  
141 if (!defined $context) {
142 $context = $self->get_context;
143 }
144  
145 if (!defined $context) {
146 # Still no context? Need to parse.
147 my $parser = XML::XPath::XMLParser->new(
148 filename => $self->get_filename,
149 xml => $self->get_xml,
150 ioref => $self->get_ioref,
151 parser => $self->get_parser,
152 );
153 $context = $parser->parse;
154 $self->set_context($context);
155 #warn "CONTEXT:\n", Dumper([$context], ['context']);
156 }
157  
158 my $parsed_path = $self->{path_parser}->parse($path);
159 #warn "\n\nPATH: ", $parsed_path->as_string, "\n\n";
160  
161 #warn "evaluating path\n";
162 return $parsed_path->evaluate($context);
163 }
164  
165 =head2 findnodes($path, [$context])
166  
167 Returns a list of nodes found by $path, optionally in context $context. In scalar
168 context returns an XML::XPath::NodeSet object.
169  
170 =cut
171  
172 sub findnodes {
173 my ($self, $path, $context) = @_;
174  
175 my $results = $self->find($path, $context);
176  
177 if ($results->isa('XML::XPath::NodeSet')) {
178 return wantarray ? $results->get_nodelist : $results;
179 }
180  
181 # warn("findnodes returned a ", ref($results), " object\n") if $XML::XPath::Debug;
182 return wantarray ? () : XML::XPath::NodeSet->new();
183 }
184  
185 =head2 matches($node, $path, [$context])
186  
187 Returns true if the node matches the path (optionally in context $context).
188  
189 =cut
190  
191 sub matches {
192 my $self = shift;
193 my ($node, $path, $context) = @_;
194  
195 my @nodes = $self->findnodes($path, $context);
196  
197 if (grep { "$node" eq "$_" } @nodes) {
198 return 1;
199 }
200 return;
201 }
202  
203 =head2 findnodes_as_string($path, [$context])
204  
205 Returns the nodes found reproduced as XML.The result is'nt guaranteed to be valid
206 XML though.
207  
208 =cut
209  
210 sub findnodes_as_string {
211 my ($self, $path, $context) = @_;
212  
213 my $results = $self->find($path, $context);
214  
215 if ($results->isa('XML::XPath::NodeSet')) {
216 return join('', map { $_->toString } $results->get_nodelist);
217 }
218 elsif ($results->isa('XML::XPath::Node')) {
219 return $results->toString;
220 }
221 else {
222 return XML::XPath::Node::XMLescape($results->value);
223 }
224 }
225  
226 =head2 findvalue($path, [$context])
227  
228 Returns either a C<XML::XPath::Literal>, a C<XML::XPath::Boolean> or a C<XML::XPath::Number>
229 object.If the path returns a NodeSet,$nodeset->to_literal is called automatically
230 for you (and thus a C<XML::XPath::Literal> is returned).Note that for each of the
231 objects stringification is overloaded, so you can just print the value found, or
232 manipulate it in the ways you would a normal perl value (e.g. using regular expressions).
233  
234 =cut
235  
236 sub findvalue {
237 my ($self, $path, $context) = @_;
238  
239 my $results = $self->find($path, $context);
240 if ($results->isa('XML::XPath::NodeSet')) {
241 return $results->to_literal;
242 }
243  
244 return $results;
245 }
246  
247 =head2 exists($path, [$context])
248  
249 Returns true if the given path exists.
250  
251 =cut
252  
253 sub exists {
254 my ($self, $path, $context) = @_;
255  
256 $path = '/' if (!defined $path);
257 my @nodeset = $self->findnodes($path, $context);
258 return 1 if (scalar( @nodeset ));
259 return 0;
260 }
261  
262 sub getNodeAsXML {
263 my ($self, $node_path) = @_;
264  
265 $node_path = '/' if (!defined $node_path);
266 if (ref($node_path)) {
267 return $node_path->as_string();
268 } else {
269 return $self->findnodes_as_string($node_path);
270 }
271 }
272  
273 =head2 getNodeText($path)
274  
275 Returns the L<XML::XPath::Literal> for a particular XML node. Returns a string if
276 exists or '' (empty string) if the node doesn't exist.
277  
278 =cut
279  
280 sub getNodeText {
281 my ($self, $node_path) = @_;
282  
283 if (ref($node_path)) {
284 return $node_path->string_value();
285 } else {
286 return $self->findvalue($node_path);
287 }
288 }
289  
290 =head2 setNodeText($path, $text)
291  
292 Sets the text string for a particular XML node. The node can be an element or an
293 attribute. If the node to be set is an attribute, and the attribute node does not
294 exist, it will be created automatically.
295  
296 =cut
297  
298 sub setNodeText {
299 my ($self, $node_path, $new_text) = @_;
300  
301 my $nodeset = $self->findnodes($node_path);
302 return undef if (!defined $nodeset);
303  
304 my @nodes = $nodeset->get_nodelist;
305 if ($#nodes < 0) {
306 if ($node_path =~ m{/(?:@|attribute::)([^/]+)$}) {
307 # attribute not found, so try to create it
308  
309 # Based upon the 'perlvar' documentation located at:
310 # http://perldoc.perl.org/perlvar.html
311 #
312 # The @LAST_MATCH_START section indicates that there's a more efficient
313 # version of $` that can be used.
314 #
315 # Specifically, after a match against some variable $var:
316 # * $` is the same as substr($var, 0, $-[0])
317 my $parent_path = substr($node_path, 0, $-[0]);
318 my $attr = $1;
319 $nodeset = $self->findnodes($parent_path);
320 return undef if (!defined $nodeset);
321 foreach my $node ($nodeset->get_nodelist) {
322 my $newnode = XML::XPath::Node::Attribute->new($attr, $new_text);
323 return undef if (!defined $newnode);
324 $node->appendAttribute($newnode);
325 }
326 } else {
327 return undef;
328 }
329 }
330  
331 foreach my $node (@nodes) {
332 if ($node->getNodeType == XML::XPath::Node::ATTRIBUTE_NODE) {
333 $node->setNodeValue($new_text);
334 } else {
335 foreach my $delnode ($node->getChildNodes()) {
336 $node->removeChild($delnode);
337 }
338 my $newnode = XML::XPath::Node::Text->new($new_text);
339 return undef if (!defined $newnode);
340 $node->appendChild($newnode);
341 }
342 }
343  
344 return 1;
345 }
346  
347 =head2 createNode($path)
348  
349 Creates the node matching the C<$path> given. If part of the path given or all of
350 the path do not exist, the necessary nodes will be created automatically.
351  
352 =cut
353  
354 sub createNode {
355 my ($self, $node_path) = @_;
356  
357 my $path_steps = $self->{path_parser}->parse($node_path);
358 my @path_steps = ();
359 foreach my $step (@{$path_steps->get_lhs()}) {
360 my $string = $step->as_string();
361 push(@path_steps, $string) if (defined $string && $string ne "");
362 }
363  
364 my $prev_node = undef;
365 my $nodeset = undef;
366 my $nodes = undef;
367 my $p = undef;
368 my $test_path = "";
369 # Start with the deepest node, working up the path (right to left),
370 # trying to find a node that exists.
371 for ($p = $#path_steps; $p >= 0; $p--) {
372 my $path = $path_steps[$p];
373 $test_path = "(/" . join("/", @path_steps[0..$p]) . ")";
374 $nodeset = $self->findnodes($test_path);
375 return undef if (!defined $nodeset); # error looking for node
376 $nodes = $nodeset->size;
377 return undef if ($nodes > 1); # too many paths - path not specific enough
378 if ($nodes == 1) { # found a node -- need to create nodes below it
379 $prev_node = $nodeset->get_node(1);
380 last;
381 }
382 }
383 if (!defined $prev_node) {
384 my @root_nodes = $self->findnodes('/')->get_nodelist();
385 $prev_node = $root_nodes[0];
386 }
387  
388 # We found a node that exists, or we'll start at the root.
389 # Create all lower nodes working left to right along the path.
390 for ($p++ ; $p <= $#path_steps; $p++) {
391 my $path = $path_steps[$p];
392 my $newnode = undef;
393 my($axis,$name) = ($path =~ /^(.*?)::(.*)$/);
394 if ($axis =~ /^child$/i) {
395 if ($name =~ /(\S+):(\S+)/) {
396 $newnode = XML::XPath::Node::Element->new($name, $1);
397 } else {
398 $newnode = XML::XPath::Node::Element->new($name);
399 }
400 return undef if (!defined $newnode);
401 $prev_node->appendChild($newnode);
402 } elsif ($axis =~ /^attribute$/i) {
403 if ($name =~ /(\S+):(\S+)/) {
404 $newnode = XML::XPath::Node::Attribute->new($name, "", $1);
405 } else {
406 $newnode = XML::XPath::Node::Attribute->new($name, "");
407 }
408 return undef if (!defined $newnode);
409 $prev_node->appendAttribute($newnode);
410 }
411 $prev_node = $newnode;
412 }
413  
414 return $prev_node;
415 }
416  
417 sub get_filename {
418 my $self = shift;
419 $self->{_filename};
420 }
421  
422 sub set_filename {
423 my $self = shift;
424 $self->{_filename} = shift;
425 }
426  
427 sub get_parser {
428 my $self = shift;
429 $self->{_parser};
430 }
431  
432 sub set_parser {
433 my $self = shift;
434 $self->{_parser} = shift;
435 }
436  
437 sub get_xml {
438 my $self = shift;
439 $self->{_xml};
440 }
441  
442 sub set_xml {
443 my $self = shift;
444 $self->{_xml} = shift;
445 }
446  
447 sub get_ioref {
448 my $self = shift;
449 $self->{_ioref};
450 }
451  
452 sub set_ioref {
453 my $self = shift;
454 $self->{_ioref} = shift;
455 }
456  
457 sub get_context {
458 my $self = shift;
459 $self->{_context};
460 }
461  
462 sub set_context {
463 my $self = shift;
464 $self->{_context} = shift;
465 }
466  
467 sub cleanup {
468 my $self = shift;
469 if ($XML::XPath::SafeMode) {
470 my $context = $self->get_context;
471 return unless $context;
472 $context->dispose;
473 }
474 }
475  
476 =head2 set_namespace($prefix, $uri)
477  
478 Sets the namespace prefix mapping to the uri.
479  
480 Normally in C<XML::XPath> the prefixes in XPath node test take their context from
481 the current node. This means that foo:bar will always match an element <foo:bar>
482 regardless of the namespace that the prefix foo is mapped to (which might even
483 change within the document, resulting in unexpected results). In order to make
484 prefixes in XPath node tests actually map to a real URI, you need to enable that
485 via a call to the set_namespace method of your C<XML::XPath> object.
486  
487 =cut
488  
489 sub set_namespace {
490 my $self = shift;
491 my ($prefix, $expanded) = @_;
492 $self->{path_parser}->set_namespace($prefix, $expanded);
493 }
494  
495 =head2 clear_namespaces()
496  
497 Clears all previously set namespace mappings.
498  
499 =cut
500  
501 sub clear_namespaces {
502 my $self = shift;
503 $self->{path_parser}->clear_namespaces();
504 }
505  
506 =head2 $XML::XPath::Namespaces
507  
508 Set this to 0 if you I<don't> want namespace processing to occur. This will make
509 everything a little (tiny) bit faster, but you'll suffer for it, probably.
510  
511 =head1 Node Object Model
512  
513 See L<XML::XPath::Node>, L<XML::XPath::Node::Element>,
514 L<XML::XPath::Node::Text>, L<XML::XPath::Node::Comment>,
515 L<XML::XPath::Node::Attribute>, L<XML::XPath::Node::Namespace>,
516 and L<XML::XPath::Node::PI>.
517  
518 =head1 On Garbage Collection
519  
520 XPath nodes work in a special way that allows circular references, and yet still
521 lets Perl's reference counting garbage collector to clean up the nodes after use.
522 This should be totally transparent to the user, with one caveat: B<If you free
523 your tree before letting go of a sub-tree,consider that playing with fire and you
524 may get burned>. What does this mean to the average user? Not much. Provided you
525 don't free (or let go out of scope) either the tree you passed to XML::XPath->new,
526 or if you didn't pass a tree, and passed a filename or IO-ref, then provided you
527 don't let the XML::XPath object go out of scope before you let results of find()
528 and its friends go out of scope, then you'll be fine. Even if you B<do> let the
529 tree go out of scope before results, you'll probably still be fine. The only case
530 where you may get stung is when the last part of your path/query is either an
531 ancestor or parent axis. In that case the worst that will happen is you'll end up
532 with a circular reference that won't get cleared until interpreter destruction
533 time.You can get around that by explicitly calling $node->DESTROY on each of your
534 result nodes, if you really need to do that.
535  
536 Mail me direct if that's not clear. Note that it's not doom and gloom. It's by no
537 means perfect,but the worst that will happen is a long running process could leak
538 memory. Most long running processes will therefore be able to explicitly be
539 careful not to free the tree (or XML::XPath object) before freeing results.AxKit,
540 an application that uses XML::XPath, does this and I didn't have to make any
541 changes to the code - it's already sensible programming.
542  
543 If you I<really> don't want all this to happen, then set the variable $XML::XPath::SafeMode,
544 and call $xp->cleanup() on the XML::XPath object when you're finished, or $tree->dispose()
545 if you have a tree instead.
546  
547 =head1 Example
548  
549 Please see the test files in t/ for examples on how to use XPath.
550  
551 =head1 AUTHOR
552  
553 Original author Matt Sergeant, C<< <matt at sergeant.org> >>
554  
555 Currently maintained by Mohammad S Anwar, C<< <mohammad.anwar at yahoo.com> >>
556  
557 =head1 SEE ALSO
558  
559 L<XML::XPath::Literal>, L<XML::XPath::Boolean>, L<XML::XPath::Number>,
560 L<XML::XPath::XMLParser>, L<XML::XPath::NodeSet>, L<XML::XPath::PerlSAX>,
561 L<XML::XPath::Builder>.
562  
563 =head1 LICENSE AND COPYRIGHT
564  
565 This module is copyright 2000 AxKit.com Ltd. This is free software, and as such
566 comes with NO WARRANTY. No dates are used in this module. You may distribute this
567 module under the terms of either the Gnu GPL, or the Artistic License (the same
568 terms as Perl itself).
569  
570 For support, please subscribe to the L<Perl-XML|http://listserv.activestate.com/mailman/listinfo/perl-xml>
571 mailing list at the URL
572  
573 =cut
574  
575 1; # End of XML::XPath
« XPath/XMLParser.pm ↑ Summary XPath/Parser.pm »