开发者

Why doesn't Perl's XML::LibXML module (specifically XPathContext) evaluate positions?

开发者 https://www.devze.com 2022-12-28 03:38 出处:网络
I have an XML representation of a document that has the form: <response> <paragraph> <sentence id=\"1\">Hey</sentence>

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( '//sente开发者_开发技巧nce[@id=' . "$id]/text()");

Can position() only be used to limit a query like you have?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消