【问题标题】:PHP xpath - find element with a value and also get elements before and after elementPHP xpath - 查找具有值的元素并获取元素之前和之后的元素
【发布时间】:2011-06-08 13:34:05
【问题描述】:

假设我有这个 XML:

<images>
    <photo>
        <thumbImg>images/thumbs/002.jpg</thumbImg>
        <filename>002</filename>
    </photo>
    <photo>
        <thumbImg>images/thumbs/008.jpg</thumbImg>
        <filename>008</filename>
    </photo>
    <photo>
        <thumbImg>images/thumbs/003.jpg</thumbImg>
        <filename>003</filename>
    </photo>
    <photo>
        <thumbImg>images/thumbs/006.jpg</thumbImg>
        <filename>006</filename>
    </photo>
    <photo>
        <thumbImg>images/thumbs/005.jpg</thumbImg>
        <filename>005</filename>
    </photo>
</images>

我想找到文件名值为 003 的元素,然后找到该元素之前的元素 1 和之后的元素 1。这就是我可以获取上一个/下一个功能的数据以及在页面上显示所选图像的全部内容。我在想这样就可以了:

$image_id = "003";
$project = $xml_object->xpath("photo[filename='$image_id']");

但它的 print_r 是一个空数组... xpath 是否有一种简单的方法可以做到这一点?我想我可以通过循环并将 prev/next 元素放入一个临时数组中来做到这一点,然后一旦找到它,就打破循环并返回临时数据,但我认为 xpath 可能能够做得更多一点优雅地。

编辑:已解决 - 这是兄弟节点的更清晰答案:

// for the one prior
//photo[filename='$image_id']/preceding-sibling::photo[1]
// for the one after
//photo[filename='$image_id']/following-sibling::photo[1] 

【问题讨论】:

    标签: php xml xpath simplexml


    【解决方案1】:

    使用这个:

    $project = $xml_object->xpath("//photo[filename='$image_id']");
    

    【讨论】:

    • 太棒了,这行得通 - 你如何获得前一个和下一个元素?
    • $project = $xml_object-&gt;xpath("//photo"); while(list( , $node) = each($project)) { var_dump($node); } 将遍历整个循环。
    • 抱歉,澄清一下 - 我将如何获取之前的单个元素和之后的单个元素,而不是所有的照片元素
    • 没关系 - 明白了 - //photo[filename='$image_id']/preceding-sibling::photo[1] for the previous, //photo[filename='$image_id']/ following-sibling::photo[1] 之后的那个
    • 不错。必须记住这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 2021-11-04
    相关资源
    最近更新 更多