与last()函数相对 [英] Opposite of last() function

查看:92
本文介绍了与last()函数相对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与XPath的 last()功能相反,选择第一(显然,没有 first()

What is the opposite of XPath's last() function, to select the "first" (apparently, there is no first()) result from query?

或者,我如何模仿?

也许问题在于我使用祖先和上下文的具体示例。

Maybe the problem is with my specific example using ancestors and context.

document.html

<div id="holder" special-header="We have a special header here">
    <div class="element" special-header="And this is even more specific">
        <p id="interested">Content, content</p>
    </div>
</div>

script.php

$doc = new DOMDocument;
$doc->loadHTMLFile('document.html');
$contextNode = $document->getElementById('interested');

/* first try */
$first = $xpath->query('//ancestor::*[@special-header][1]', $contextNode);
echo $first->getAttribute('special-header'); // result == "We have a special header here" intended == "And this is even more specific"

/* second try */
$one = $xpath->query('//ancestor::*[@special-header][last()]', $contextNode); // in case it starts from "first found ancestor" and descends
echo $one->getAttribute('special-header'); // same result as before..

尝试使用 position()= 1 我再次获得相同的结果。

Trying with position()=1 I get the same result again.

推荐答案

问题是表达式的含义 // ancestor :: * [@ special-header] 相当含糊,因为 // 强制从根节点搜索。

The problem is that the meaning of the expression //ancestor::*[@special-header] is rather vague, because // forces searching from the root node.

解决方案是删除表达式开头的 //

The solution is to remove the // at the beginning of the expressions.

BTW,你的代码实际上不工作=)。这是修正版本:

BTW, your code is actually not working =). Here is the corrected version:

$html = <<<HTML
<div id="holder" special-header="We have a special header here">
    <div class="element" special-header="And this is even more specific">
        <p id="interested">Content, content</p>
    </div>
</div>
HTML;

$doc = new DOMDocument();
$doc->loadHTML($html);
$contextNode = $doc->getElementById('interested');
$xpath = new DOMXpath($doc);

$first = $xpath->query('ancestor::*[@special-header][1]',
                       $contextNode) -> item(0);
echo $first->getAttribute('special-header') . "\n";

$one = $xpath->query('ancestor::*[@special-header][last()]',
                     $contextNode)-> item(0);
echo $one->getAttribute('special-header') . "\n"; 

结果:

C:\>\php\php.exe dom_games.php
And this is even more specific
We have a special header here

这篇关于与last()函数相对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆