关于查询路径的 2 个基本问题


2 fundamental questions about querypath

  1. 如何查找节点是否存在?我正在使用

    if ( $item->branch((->

    siblings($tagNames['desc'](->text(((

有没有更好的方法?

  1. 有没有办法执行OR查询? 如果标签 A 存在,则获取其 text((,否则获取 B 的文本(( ?

我正在使用以下内容:

 $desc1 = (  $item->branch()->siblings($tagNames['desc'])->text()  ?
$item->branch()->siblings($tagNames['desc'])   :
$item->branch()->siblings($tagNames['descAlternative']) ) ;

这看起来不像是最有效的做事方式。

谢谢

关于第一个:

当 QueryPath 找不到匹配项时,它的大小为 0。所以你可以做到:

if (count($item) > 0) {
  // do whatever with $item
}

因此,对于第二个示例,您可以执行以下操作:

if (count($item->branch()->siblings($tagNames['desc']))) {
    $item->branch()->siblings($tagNames['desc']);
    $item->branch()->siblings($tagNames['descAlternative']) ) ;
}

但还有另一种方法:您也可以一次传入两个选择器。

$item->branch()->siblings('desc, descAlternative')->text();

这将选择两者。但是,text()将仅返回第一个匹配项的文本。所以它具有做OR的效果。