【发布时间】: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]
【问题讨论】: