I have an XML representation of a document that has the form:
<response>
<paragraph>
<sentence id="1">Hey</sentence>
<sentence id="2">Hello</sentence>
</paragraph>
</response>
I'm trying to use XML::LibXML to parse a document and get the position of the sentences.
my $root_node = XML::LibXML->load_xml( ... )->documentElement;
foreach my $sentence_node ( $root_node->findnodes('//sentence')->get_nodelist ){
print $sentence_node->find( 'position()' );
}
The error I get is "XPath error : Invalid context position error". I've read up on the docs and found this interesting tidbit
evaluating XPath function position() in the initial context raises an XPath error
My problem is that I have no idea what to do with this information. What is the 'initial context'? How do I make the engine automatically track the context position?
Re: @Dan
Appreciate the answer. I tried your example and it worked. In my code, I was assuming context to be the node represented by my perl variable. So, $sentence->find( 'position()' ) I wanted to be './position()'. Despite seeing a working example, I still can't do
foreach my $sentence ...
my $id = $sentence->getAttribute('id');
print $root_node->findvalue( '//sentence[@id=' . "$id]/position()");
I can, however, do
$root_node->findvalue( '//sentence[@id=' . "$id]/text()");
Can position() only be used to limit a query like you have?