Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search by XPath under a given element

Tags:

The only way I know in PHP to perform an XPath query on the DOM is DOMXPath, which only works on a DOMDocument:

public __construct ( DOMDocument $doc ) 

Is there a similar mechanism to search relatively to a DOMElement?

The problem being, I need to search an abritrary XPath (that I have no control over) relatively to a DOMElement.

I've tried to do:

$domElement->getNodePath() . '/' . $xPath; 

But if the XPath contains a | (or character), this approach doesn't work.

like image 218
BenMorel Avatar asked May 03 '13 17:05

BenMorel


People also ask

How do you get to the nth sub element using the XPath?

By adding square brackets with index. By using position () method in xpath.


1 Answers

Yes there is. The element is also part of the document, so you use the xpath object of the document, but when you run the query, there is a second parameter which is the context-node to which the query in the first parameter is resolved to:

// query all child-nodes of $domElement $result = $xpath->query('./*', $domElement); 

Resolved means, that if the xpath is:

  1. relative, it is relative to that $domElement context-node.
  2. absolute, it resolves to the document node (still/again).

Only relative path applies in context here, which is why I prefixed it with a dot in front: ./*. A simple * would work, too, just would not make this specifically visible.

See DOMXpath::query().

like image 80
hakre Avatar answered Sep 18 '22 05:09

hakre