| 1 | #!/usr/bin/env perl | ||
| 2 | # XML::Axk::Matcher::XPath - XPath matcher | ||
| 3 | # Reminder: all matchers define test($refdata)->bool. | ||
| 4 | # Copyright (c) 2018 cxw42. All rights reserved. Artistic 2. | ||
| 5 | |||
| 6 | package XML::Axk::Matcher::XPath; | ||
| 7 | 1 | ▶ | use XML::Axk::Base qw(:default any); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 8 | 1 | ▶ | use XML::Axk::DOM; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 9 | |||
| 10 | our $VERBOSE = 0; | ||
| 11 | |||
| 12 | use Object::TinyDefaults | ||
| 13 | { kind => 'xpath', | ||
| 14 | file => '(unknown source)', | ||
| 15 | line => 0 | ||
| 16 | }, | ||
| 17 | qw(xpath); | ||
| 18 | |||
| 19 | sub _dump { | ||
| 20 | local $Data::Dumper::Maxdepth = 2; | ||
| 21 | Dumper @_; | ||
| 22 | } #_dump() | ||
| 23 | |||
| 24 | # Constructor and worker ================================================ | ||
| 25 | |||
| 26 | sub new { | ||
| 27 | my $class = shift; | ||
| 28 | my $self = $class->SUPER::new(@_); | ||
| 29 | croak "No xpath specified" unless $self->{xpath}; | ||
| 30 | |||
| 31 | return $self; | ||
| 32 | } #new() | ||
| 33 | |||
| 34 | # Determine if the record indicated in $hrCP matches the xpath we have stored. | ||
| 35 | sub test { | ||
| 36 | my $self = shift; | ||
| 37 | my $hrCP = shift or return false; # Core params | ||
| 38 | |||
| 39 | eval { | ||
| 40 | say "XPath: Attempt to match `$self->{xpath}' in ", $self->file, | ||
| 41 | ' at ', $self->line, ' against ', ref $hrCP->{record}; | ||
| 42 | say _dump $hrCP if $VERBOSE>1; | ||
| 43 | } if $VERBOSE>0; | ||
| 44 | |||
| 45 | # Works, but slow | ||
| 46 | #my @matches = $hrCP->{document}->findnodes($self->xpath); | ||
| 47 | #say "XPath matches: ", _dump(\@matches) if $VERBOSE>0; | ||
| 48 | #return any { $_ == $hrCP->{record} } @matches; | ||
| 49 | |||
| 50 | # Works. We have to use the xp directly because XML::DOM::XPath v0.14 L59 | ||
| 51 | # (https://metacpan.org/source/MIROD/XML-DOM-XPath-0.14/XPath.pm#L59) | ||
| 52 | # swaps the order of the document and node parameters in the call to | ||
| 53 | # xp->matches(). | ||
| 54 | return $hrCP->{document}->xp->matches( | ||
| 55 | $hrCP->{record}, # element | ||
| 56 | $self->xpath, # path | ||
| 57 | $hrCP->{document} # context | ||
| 58 | ); | ||
| 59 | |||
| 60 | } #test() | ||
| 61 | |||
| 62 | 1; | ||
| 63 | # vi: set ts=4 sts=4 sw=4 et ai fo-=ro foldmethod=marker: # | ||