php-xpath选择元素,然后选择子元素

问题描述 投票:0回答:1

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

xpath
1个回答
0
投票

我想出了这个:

$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;

© www.soinside.com 2019 - 2024. All rights reserved.