In your node class, use Class::XPath:
# generate xpath() and match() using Class::XPath
use Class::XPath
get_name => 'name', # get the node name with the 'name' method
get_parent => 'parent', # get parent with the 'parent' method
get_root => \&get_root, # call get_root($node) to get the root
get_children => 'kids', # get children with the 'kids' method
get_attr_names => 'param', # get names and values of attributes
get_attr_value => 'param', # from param
get_content => 'data', # get content from the 'data' method
;
Now your objects support XPath-esque matching:
# find all pages, anywhere in the tree
@nodes = $node->match('//page');
# returns an XPath like "/page[1]/paragraph[2]"
$xpath = $node->xpath();
=head1 DESCRIPTION
This module adds XPath-style matching to your object trees. This
means that you can find nodes using an XPath-esque query with
C<match()> from anywhere in the tree. Also, the C<xpath()> method
returns a unique path to a given node which can be used as an
identifier.
To use this module you must already have an OO implementation of a
tree. The tree must be a true tree - all nodes have a single parent
and the tree must have a single root node. Also, the order of
children within a node must be stable.
B<NOTE:> This module is not yet a complete XPath implementation. Over
time I expect the subset of XPath supported to grow. See the SYNTAX
documentation for details on the current level of support.
=head1 USAGE
This module is used by providing it with information about how your
class works. Class::XPath uses this information to build the
C<match()> and C<xpath()> methods for your class. The parameters
passed to 'use Class::XPath' may be set with strings, indicating
method names, or subroutine references. They are:
=over
=item get_name (required)
Returns the name of this node. This will be used as the element name
when evaluating an XPath match. The value returned must matches
/^[\w:]+$/.
=item get_parent (required)
Returns the parent of this node. The root node must return undef from
the get_parent method.
=item get_children (required)
Returns a list of child nodes, in order.
=item get_attr_names (required)
Returns a list of available attribute names. The values returned must
match /^[\w:]+$/).
=item get_attr_value (required)
Called with a single parameter, the name of the attribute. Returns
the value associated with that attribute. The value returned must be
C<undef> if no value exists for the attribute.
=item get_content (required)
Returns the contents of the node. In XML this is text between start
and end tags.
=item get_root (required)
Returns the root node of this tree.
=item call_match (optional)
Set this to the name of the C<match()> method to generate. Defaults
to 'match'.
=item call_xpath (optional)
Set this to the name of the C<xpath()> method to generate. Defaults
to 'xpath'.
=4= |