=back
=head2 ALTERNATE USAGE
If you're using someone else's OO tree module, and you don't want to
subclass it, you can still use Class::XPath to add XPath matching to
it. This is done by calling C<Class::XPath->add_methods()> with all
the options usually passed to C<use> and one extra one, C<target>.
For example, to add xpath() and match() to HTML::Element (the node
class for HTML::TreeBuilder):
# add Class::XPath routines to HTML::Element
Class::XPath->add_methods(target => 'HTML::Element',
get_parent => 'parent',
get_name => 'tag',
get_attr_names =>
sub { my %attr = shift->all_external_attr;
return keys %attr; },
get_attr_value =>
sub { my %attr = shift->all_external_attr;
return $attr{$_[0]}; },
get_children =>
sub { grep { ref $_ } shift->content_list },
get_content =>
sub { grep { not ref $_ } shift->content_list },
get_root =>
sub { local $_=shift;
while($_->parent) { $_ = $_->parent }
return $_; });
Now you can load up an HTML file and do XPath matching on it:
my $root = HTML::TreeBuilder->new;
$root->parse_file("foo.html");1
# get a list of all paragraphs
my @paragraphs = $root->match('//p');
# get the title element
my ($title) = $root->match('/head/title');
=head1 GENERATED METHODS
This module generates two public methods for your class:
=over
=item C<< @results = $node->match('/xpath/expression') >>
This method performs an XPath match against the tree to which this
node belongs. See the SYNTAX documentation for the range of supported
expressions. The return value is either a list of node objects, a list
of values (when retrieving specific attributes) or an empty list if no
matches could be found. If your XPath expression cannot be parsed then
the method will die.
You can change the name of this method with the 'call_match' option
described above.
=item C<< $xpath = $node->xpath() >>
Get an xpath to uniquely identify this node. Can be used with match()
to find the element later. The xpath returned is guaranteed to be
unqiue within the element tree. For example, the third node named
"paragraph" inside node named "page" has the xpath
"/page[1]/paragraph[2]".
You can change the name of this method with the 'call_xpath' option
described above.
=back
=head1 SYNTAX
This module supports a small subset of XPath at the moment. Here is a
list of the type of expressions it knows about:
=over
=item .
Selects and returns the current node.
=item name
=item ./name
Selects a list of nodes called 'name' in the tree below the current
node.
=item /name
Selects a list of nodes called 'name' directly below the root of the
tree.
=item //name
Selects all nodes with a matching name, anywhere in the tree.
=5= |