views:

134

answers:

1

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?

+2  A: 

position() does work in LibXML. For example see

my $root_node = $doc->documentElement;
foreach my $sentence_node ( $root_node->findnodes('//sentence[position()=2]')->get_nodelist ){
  print $sentence_node->textContent;
}

This will print Hello with your sample data.

But the way you're using it here, there's no context. For each sentence_node, you want its position relative to what?

If you're looking for specific nodes by position, use a selector like I have above, that's simplest.

Dan
What I'm really looking for is the position of a node I already have. Does my edited question give more insight to the problem?
Brian C