I am trying to access a specific element of the Dom using XPath
Here is an example
<table>
<tbody>
<tr>
<td>
<b>1</b> <a href="http://www.url.html">data</a><br>
<b>2</b> <a href="http://www.url.html">data</a><br>
<b>3</b> <a href="http://www.url.html">data</a><br>
</td>
</tr>
</tbody>
</table>
I want to target “table td” so my query in Xpath is something like
$finder->query('//table/td');
only this doesn’t return the td as its a sub child and direct access would be done using
$finder->query('//tr/td');
Is there a better way to write the query which would allow me to use something like the first example ignoring the elements in-between and return the TD?
You can write:
However, is this really “better”?
In many cases the evaluation of the XPath pseudo-operator
//can result in significant inefficiency as it causes the whole subtree rooted in the context-node to be traversed.Whenever the path to the wanted nodes is statically known, it may be more efficient to replace any
//with the specific, known path, thus avoiding the complete subtree traversal.For the provided XML document, such expression is:
If there is more than one
tableelement, each a child of the top element and we want to select only thetds of the forsttable, a good, specific expression is:If we want to select only the first
tdof the firsttablein the same document, a good way to do this would be:Or if we want to select the first
tdin the XML document (not knowing its structure in advance), then we could specify this: