xpath中有没有一种方法可以选择一个元素,而不是选择该元素的子代?
即给定父级结果,我如何找到相对于this
paraent
假设以下代码:
<div class="product-general" prod-id="4407">
<img src="..."/>
<div class="prod-name">Black Dog</div>
</div>
在jQuery
中可以做到:
parent = $('.product-general')
id = parent.attr('prod-id')
name = $('.prod-name', parent).text()
我有以下代码(php):
$results = $xpath->query("//*[@class='product-general']");
for ($i = 0; $i < $results->length; $i++) {
$parent = $results->item($i)->nodeValue;
// todo: get prod-id and prod-name
}
是否可能获得相对于父代的prod-id和prod-name?
注意:我知道我可以按照以下步骤操作:
$results = $xpath->query("//*[@class='product-general']/@data-pid");
for ($i = 0; $i < $results->length; $i++) {
$pid = $results->item($i)->nodeValue;
$results2 = $xpath->query("//*[@class='product-general' and @data-pid='".$pid."']//*[contains(@class,'prod-name')]");//
$name= $results2->item(0)->nodeValue;
$this->products[] = ['pid' => $pid, 'name' => $name];
}
但是我想知道是否还有更优雅的东西,例如JQ示例
此外,对于具有1000种产品的文档,此解决方案的速度也很慢
10x
我想出了这个:
$results = $xpath->query("//*[@id='searchPage']//article");
for ($i = 0; $i < $results->length; $i++) {
$counter = $i+1;
$href = $xpath->query("//*[@id='searchPage']//article[".$counter."]/a/@href")->item(0)->nodeValue;
}
此代码将在article
中的所有searchPage
上循环并提取其<a href="...">
关键思想是,通过将[".$counter."]
添加到查询中,u可以将当前循环索引用作搜索子元素的上下文
注意$counter = $i+1;