Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
875 views
in Technique[技术] by (71.8m points)

xml - PHP xpath - find element with a value and also get elements before and after element

Lets say I have this 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>

And I want to find the element with the filename value of 003 and then find the elements 1 prior and 1 after that element. This is all so I can get the data for a prev/next functionality as well as show the selected image on a page. I was thinking this would do it:

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

But it print_r's an empty array... Is there an easy way with xpath to do this perhaps? I figured that I could do it by just looping through and putting the prev/next elements into a temp array, then once it's found, break the loop and return the temp data, but I thought xpath might be able to do it a little more elegantly.

EDIT: solved - here's the clearer answer for the sibling nodes:

// for the one prior
//photo[filename='$image_id']/preceding-sibling::photo[1]
// for the one after
//photo[filename='$image_id']/following-sibling::photo[1] 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...