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