Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

libxml2: xpath relative to sub node

Tags:

xpath

libxml2

Given the xml file

<a>
   <b>
      <d>v</d>
   </b>
   <c>
      <d>v</d>
   </c>
</a>

And the xpath "//d/text()"

I want to apply the xpath only to c and not to the whole document.

This has to work with libxml2 2.7.6

Doing this does not work;

xmlNodePtr node = <node pointer to c>
xmlXPathContextPtr xpathCtx = xmlXPathNewContext( node->doc );
xpathCtx->node = node;

xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression ( "//d/text()", xpathCtx);

Returned xpathObj contains refences to both /a/b/d and /a/c/d. Only /a/c/d was expected.

like image 718
Nicola Vacca Avatar asked Mar 24 '26 16:03

Nicola Vacca


1 Answers

Use the path .//d or .//d/text() if you want to find descendants relative to another node. A path starting with //d searches all d descendant elements of the root node (also called document node).

like image 147
Martin Honnen Avatar answered Mar 27 '26 15:03

Martin Honnen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!