XML::Li...hContext(3)

✨ NAME ✨

XML::LibXML::XPathContext β€” XPath Evaluation πŸ’…

okay so bestie, welcome to XML::LibXML::XPathContext(3), straight out of the User Contributed Perl Documentation section. this is the one that lets you do XPath stuff. buckle up πŸŽ€


✨ SYNOPSIS ✨

like, here's the whole vibe of what you can call:

my $xpc = XML::LibXML::XPathContext->new();
my $xpc = XML::LibXML::XPathContext->new($node);
$xpc->registerNs($prefix, $namespace_uri)
$xpc->unregisterNs($prefix)
$uri = $xpc->lookupNs($prefix)
$xpc->registerVarLookupFunc($callback, $data)
$data = $xpc->getVarLookupData();
$callback = $xpc->getVarLookupFunc();
$xpc->unregisterVarLookupFunc($name);
$xpc->registerFunctionNS($name, $uri, $callback)
$xpc->unregisterFunctionNS($name, $uri)
$xpc->registerFunction($name, $callback)
$xpc->unregisterFunction($name)
@nodes = $xpc->findnodes($xpath_expression)
@nodes = $xpc->findnodes($xpath_expression, $context_node )
$nodelist = $xpc->findnodes($xpath_expression, $context_node )
$object = $xpc->find($xpath_expression )
$object = $xpc->find($xpath_expression, $context_node )
$value = $xpc->findvalue($xpath_expression )
$value = $xpc->findvalue($xpath_expression, $context_node )
$bool = $xpc->exists( $xpath_expression, $context_node );
$xpc->setContextNode($node)
my $node = $xpc->getContextNode;
$xpc->setContextPosition($position)
my $position = $xpc->getContextPosition;
$xpc->setContextSize($size)
my $size = $xpc->getContextSize;
$xpc->setContextNode($node)

✨ DESCRIPTION ✨

spilling the tea β˜• the XML::LibXML::XPathContext class hands you an almost complete interface to libxml2's XPath implementation. almost complete, bestie, don't come for me, that's what it says.

with XML::LibXML::XPathContext you can:

  • evaluate XPath expressions in the context of an arbitrary node, a context size, and a context position 🎯
  • use a user-defined namespace-prefix mapping ✨
  • write custom XPath functions in Perl (yes, in Perl, we're fancy) πŸ’…
  • and even plug in a custom XPath variable resolver πŸ‘‘

✨ EXAMPLES ✨

🌸 Namespaces 🌸

this one is showing off the registerNs() method. it hunts down every paragraph node in an XHTML document. iconic behaviour, honestly.

my $xc = XML::LibXML::XPathContext->new($xhtml_doc);
$xc->registerNs('xhtml', 'http://www.w3.org/1999/xhtml');
my @nodes = $xc->findnodes('//xhtml:p');

πŸ¦‹ Custom XPath functions πŸ¦‹

this example is serving registerFunction() realness by defining a function that filters nodes based on a Perl regular expression:

sub grep_nodes {
  my ($nodelist,$regexp) =  @_;
  my $result = XML::LibXML::NodeList->new;
  for my $node ($nodelist->get_nodelist()) {
    $result->push($node) if $node->textContent =~ $regexp;
  }
  return $result;
};

my $xc = XML::LibXML::XPathContext->new($node);
$xc->registerFunction('grep_nodes', \&grep_nodes);
my @nodes = $xc->findnodes('//section[grep_nodes(para,"\bsearch(ing|es)?\b")]');

πŸ“ Variables πŸ“

this one demos the registerVarLookup() method. the whole point? recycling results of previous evaluations like the eco-friendly queen you are ♻️

sub var_lookup {
  my ($varname,$ns,$data)=@_;
  return $data->{$varname};
}

my $areas = XML::LibXML->new->parse_file('areas.xml');
my $empl = XML::LibXML->new->parse_file('employees.xml');

my $xc = XML::LibXML::XPathContext->new($empl);

my %variables = (
  A => $xc->find('/employees/employee[@salary>10000]'),
  B => $areas->find('/areas/area[district='Brooklyn']/street'),
);

# get names of employees from $A working in an area listed in $B
$xc->registerVarLookupFunc(\&var_lookup, \%variables);
my @nodes = $xc->findnodes('$A[work_area/street = $B]/name');

✨ METHODS ✨

πŸ’– new πŸ’–

my $xpc = XML::LibXML::XPathContext->new();

creates a brand new XML::LibXML::XPathContext object without a context node. a blank canvas, a fresh start, main character energy ✨

my $xpc = XML::LibXML::XPathContext->new($node);

creates a new XML::LibXML::XPathContext object with the context node already set to $node. ready to go, no warm-up needed πŸ’…

πŸ’– registerNs πŸ’–

$xpc->registerNs($prefix, $namespace_uri)

registers namespace $prefix to $namespace_uri. matchmaker, matchmaker 🫢

πŸ’– unregisterNs πŸ’–

$xpc->unregisterNs($prefix)

unregisters namespace $prefix. it's not you, it's... actually it is you. bye πŸ’€

πŸ’– lookupNs πŸ’–

$uri = $xpc->lookupNs($prefix)

returns the namespace URI registered with $prefix. and if $prefix isn't registered to any namespace URI at all? it returns undef. not found bestie 😭

πŸ’– registerVarLookupFunc πŸ’–

$xpc->registerVarLookupFunc($callback, $data)

registers a variable lookup function $callback. the XPath engine runs that registered function every single time an XPath variable gets evaluated. it takes three arguments: $data, the variable name, and the variable ns-URI. and it must return one value:

  • a number or string
  • or any XML::LibXML:: object that can be a result of findnodes: Boolean, Literal, Number, Node (e.g. Document, Element, etc.), or NodeList

for convenience, simple (non-blessed) array references containing only XML::LibXML::Node objects can be used instead of an XML::LibXML::NodeList. we love a shortcut πŸŽ€

πŸ’– getVarLookupData πŸ’–

$data = $xpc->getVarLookupData();

returns the data that got associated with a variable lookup function during a previous call to registerVarLookupFunc. it remembers everything. unlike your ex πŸ™ˆ

πŸ’– getVarLookupFunc πŸ’–

$callback = $xpc->getVarLookupFunc();

returns the variable lookup function that was previously registered with registerVarLookupFunc.

πŸ’– unregisterVarLookupFunc πŸ’–

$xpc->unregisterVarLookupFunc($name);

unregisters the variable lookup function and the associated lookup data. both. gone. periodt πŸ’…

πŸ’– registerFunctionNS πŸ’–

$xpc->registerFunctionNS($name, $uri, $callback)

registers an extension function $name in the $uri namespace. $callback must be a CODE reference, no substitutions.

the arguments of the callback function are either simple scalars or XML::LibXML::* objects, depending on the XPath argument types. the function itself is responsible for checking the argument number and types β€” yes, that's on you, bestie, do your own vibe check βœ…

the result of the callback code must be a single value of the following types:

  • a simple scalar (number, string)
  • or an arbitrary XML::LibXML::* object that can be a result of findnodes: Boolean, Literal, Number, Node (e.g. Document, Element, etc.), or NodeList

and again, for convenience: simple (non-blessed) array references containing only XML::LibXML::Node objects can be used instead of a XML::LibXML::NodeList 🌈

πŸ’– unregisterFunctionNS πŸ’–

$xpc->unregisterFunctionNS($name, $uri)

unregisters extension function $name in the $uri namespace. has the exact same effect as passing undef as $callback to registerFunctionNS. same energy, less typing.

πŸ’– registerFunction πŸ’–

$xpc->registerFunction($name, $callback)

same as registerFunctionNS but without a namespace. minimalism, we love her.

πŸ’– unregisterFunction πŸ’–

$xpc->unregisterFunction($name)

same as unregisterFunctionNS but without a namespace.

πŸ’– findnodes πŸ’–

@nodes = $xpc->findnodes($xpath_expression)

@nodes = $xpc->findnodes($xpath_expression, $context_node )

$nodelist = $xpc->findnodes($xpath_expression, $context_node )

performs the xpath statement on the current node and returns the result as an array. in scalar context, it returns an XML::LibXML::NodeList object instead. optionally, you can pass a node as a second argument to set the context node for the query 🎯

and the xpath expression can be passed either as a string, or as a XML::LibXML::XPathExpression object. your choice, both slay.

πŸ’– find πŸ’–

$object = $xpc->find($xpath_expression )

$object = $xpc->find($xpath_expression, $context_node )

performs the xpath expression using the current node as the context of the expression, and returns the result depending on what type of result the XPath expression had. for example, the XPath 1 * 3 + 52 results in an XML::LibXML::Number object being returned. other expressions might return a XML::LibXML::Boolean object, or a XML::LibXML::Literal object (a string) πŸ‘‘

each of those objects uses Perl's overload feature to "do the right thing" in different contexts. it just knows. optional second argument = context node for the query.

the xpath expression can be passed either as a string, or as a XML::LibXML::XPathExpression object.

πŸ’– findvalue πŸ’–

$value = $xpc->findvalue($xpath_expression )

$value = $xpc->findvalue($xpath_expression, $context_node )

is exactly equivalent to:

$xpc->find( $xpath_expression, $context_node )->to_literal;

that is, it returns the literal value of the results. this enables you to ensure that you get a string back from your search, allowing certain shortcuts ✨ this could be used as the equivalent of <xsl:value-of select="some_xpath"/>.

optionally, a node may be passed in the second argument to set the context node for the query.

the xpath expression can be passed either as a string, or as a XML::LibXML::XPathExpression object.

πŸ’– exists πŸ’–

$bool = $xpc->exists( $xpath_expression, $context_node );

this method behaves like findnodes, except it only returns a boolean value (1 if the expression matches a node, 0 otherwise) β€” and it may be faster than findnodes, because the XPath evaluation may stop early on the first match. this is true for libxml2 >= 2.6.27, fyi 😌

for XPath expressions that do not return node-set, the method returns true if the returned value is a non-zero number or a non-empty string.

πŸ’– setContextNode πŸ’–

$xpc->setContextNode($node)

set the current context node. boom. done. 🎯

πŸ’– getContextNode πŸ’–

my $node = $xpc->getContextNode;

get the current context node. hand it over πŸ‘‘

πŸ’– setContextPosition πŸ’–

$xpc->setContextPosition($position)

set the current context position. by default this value is -1 β€” and evaluating the XPath function position() in the initial context raises an XPath error 🚨 β€” but you can set it to any value up to context size.

this usually only serves to cheat the XPath engine into returning the given position when the position() XPath function is called. setting this value to -1 restores the default behavior. so... set it back when you're done, bestie πŸ™ˆ

πŸ’– getContextPosition πŸ’–

my $position = $xpc->getContextPosition;

get the current context position.

πŸ’– setContextSize πŸ’–

$xpc->setContextSize($size)

set the current context size. by default this value is -1 β€” and evaluating the XPath function last() in the initial context raises an XPath error 🚨 β€” but it can be set to any non-negative value.

this usually only serves to cheat the XPath engine into returning the given value when the last() XPath function is called.

  • if context size is set to 0, position is automatically also set to 0.
  • if context size is positive, position is automatically set to 1.
  • setting context size to -1 restores the default behavior.

yes the automatic bits are real, no cap βœ‹

πŸ’– getContextSize πŸ’–

my $size = $xpc->getContextSize;

get the current context size.

πŸ’– setContextNode πŸ’–

$xpc->setContextNode($node)

set the current context node. (yes, again. it's listed twice. the manpage said it twice, so I say it twice. consistency queen πŸ’…)

πŸ’€ BUGS AND CAVEATS πŸ’€

okay bestie listen up because this part is IMPORTANT 🫢

XML::LibXML::XPathContext objects are reentrant, which lowkey slays β€” it means you can literally call methods of an XML::LibXML::XPathContext even from XPath extension functions that are registered with that same object, or from a variable lookup function. iconic behavior honestly πŸ’…

but on the other hand... you should rather avoid registering new extension functions, namespaces, and a variable lookup function from within extension functions and a variable lookup function. unless you genuinely want to experience untested behavior 😭 like that's the risk you're taking, no cap.

πŸ‘‘ AUTHORS πŸ‘‘

Ilya Martynov and Petr Pajas, based on XML::LibXML and XML::LibXSLT code by Matt Sergeant and Christian Glahn. πŸŽ€


🌸 HISTORICAL REMARK 🌸

prior to XML::LibXML 1.61 this module was distributed separately for maintenance reasons. the way that it used to be its own whole thing... vintage ✨


πŸ‘‘ AUTHORS πŸ‘‘

Matt Sergeant, Christian Glahn, Petr Pajas 🌈


⭐ VERSION ⭐

2.0213

2001-2007, AxKit.com Ltd.

2002-2006, Christian Glahn.

2006-2009, Petr Pajas.


πŸŽ€ LICENSE πŸŽ€

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. periodt πŸ’…


and that's the whole page bestie, we ate that fr fr πŸ“ this one came from perl v5.42.2, dated 2026-05-25, and it's the XML::LibXML::XPathContext(3) manpage β€” go forth and XPath your little heart out, ily πŸ¦‹πŸ’œ

πŸ“¦ where this page comes from