Reputation: 3737
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?
Upvotes: 0
Views: 1161
Reputation: 243539
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:
//table//td
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:
/*/*/tr/td
If there is more than one table
element, each a child of the top element and we want to select only the td
s of the forst table
, a good, specific expression is:
/*/table[1]/*/tr/td
If we want to select only the first td
of the first table
in the same document, a good way to do this would be:
(/*/table[1]/*/tr//td)[1]
Or if we want to select the first td
in the XML document (not knowing its structure in advance), then we could specify this:
(//td)[1]
Upvotes: 6
Reputation: 1002
Oh boy oh boy, there's something not seen often.
As for your first xpath query, you can just return what you want but use double // on before tagnames
But, I don't see why you don't just want to get the td's by tagname...
Upvotes: 1