PHP DOM 对 DOMNodeList 执行 xpath 查询
有没有办法对先前的 xpath 查询获得的 DOMNodeList 执行 xpath 查询?具体来说,我有以下代码:
$topicMap = new DOMDocument();
$topicMap->load('topicMap.xml');
$xpath = new DOMXpath($topicMap);
$relations = $xpath->query("/topicMap/relations");
现在,从生成的 DOMNodelist $relations
中,我想根据 的
元素。我尝试将 DOMNodeList 作为第二个参数(即上下文节点)提供给第二个 xpath 查询,如下所示:@type
属性选择各种子集。关系
$relations_translation = $xpath->query("/*[@type='translation']", $relations)
我收到以下错误:传递给 DOMXPath::query() 的参数 2 必须是以下实例DOMNode,给出的 DOMNodeList 实例。
我知道我可以一步执行两个查询,即 $relations_translation = $xpath->query("/topicMap/relations[@type='translation']")
。我之所以想分两步来做,是为了性能。 xml文档topicMap.xml非常大,relations
元素集只是其中的一小部分,而且我需要在这个集合上执行的查询数量也相对较大。因此,我认为仅遍历一次大型 xml 文档,选择 relations
元素,然后在这个小得多的节点列表上执行各种查询会更快。我还不知道是否会更快,但我想尝试一下。有没有办法做我想做的事?
预先感谢您的帮助!
Is there a way to perform an xpath query on a DOMNodeList obtained by a previous xpath query? Concretely, I have the following code:
$topicMap = new DOMDocument();
$topicMap->load('topicMap.xml');
$xpath = new DOMXpath($topicMap);
$relations = $xpath->query("/topicMap/relations");
Now, from the resulting DOMNodelist $relations
, I would like to select various subsets, depending on the @type
attribute of the relations
elements. I tried to supply the DOMNodeList as a second argument (i.e., context node) to a second xpath query, like so:
$relations_translation = $xpath->query("/*[@type='translation']", $relations)
I am receiving the following error: Argument 2 passed to DOMXPath::query() must be an instance of DOMNode, instance of DOMNodeList given
.
I know that I could perform the two queries in one step, i.e., $relations_translation = $xpath->query("/topicMap/relations[@type='translation']")
. The reason why I would like to do it in two steps is performance. The xml document topicMap.xml is very large, the set of relations
elements a small part of it, and the number of queries that I need to perform on this set also relatively large. So I am thinking that it will be faster to traverse the large xml document only once, select the relations
elements, and then perform the various queries on this much smaller list of nodes. I don't know yet whether it will be faster, but I would like to try. Is there a way to do what I want to do?
Thanks in advance for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 Ptit Xav 的建议,我提出了以下解决方案:
也就是说,我循环遍历
$relations
,检查@type
属性,然后存储关系根据预定义数组中的类型。Following the suggestion by Ptit Xav, I came up with the following solution:
That is, I loop through the
$relations
, check for the@type
attribute and then store the relations according to their type in predefined arrays.