在给定元素下由XPath搜索 [英] Search by XPath under a given element
问题描述
我在PHP中知道在DOM上执行XPath查询的唯一方法是 DOMXPath ,其中只适用于 DOMDocument
:
The only way I know in PHP to perform an XPath query on the DOM is DOMXPath, with only works on a DOMDocument
:
public __construct ( DOMDocument $doc )
是否有类似的机制来搜索相对于 DOMElement
?
Is there a similar mechanism to search relatively to a DOMElement
?
问题在于,我需要搜索一个比较少的XP $(我无法控制) c $ c> DOMElement 。
The problem being, I need to search an abritrary XPath (that I have no control over) relatively to a DOMElement
.
我试图这样做:
$domElement->getNodePath() . '/' . $xPath;
但是如果XPath包含一个 |
或字符),这种方法不起作用。
But if the XPath contains a |
(or character), this approach doesn't work.
推荐答案
是的。元素也是文档的一部分,因此您可以使用文档的xpath对象,但是当您运行查询时,还有一个第二个参数是第一个参数中的查询相对于以下内容的上下文节点: / p>
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 relative to:
// query all child-nodes of $domElement
$result = $xpath->query('./*', $domElement);
请参阅 DOMXpath :: query()
。
这篇关于在给定元素下由XPath搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!