简体   繁体   中英

Get parent element through xpath and all child elements

Ok so let's say I have some XML like this…

<blaah1 name="whatever">
<gender name="male">

<example1 baseurl="male/86644/">
<x u="lol.png"/>
<x u="haha.png"/>
<x u="name.png"/>
</example1>

<example2 baseurl="male/27827/">
<x u="page.png"/>
<x u="examp.png"/>
<x u="bottom.png"/>
</example2>

</gender>
</blaah1>

What do I need to do to display the u="" content on the end of the parent's baseurl for each child?

As far as I know, you can not do that with a single xpath expression but you would need to loop over the result. An example of such a loop:

$base = '';
foreach($xp->query('//@baseurl|//*[@baseurl]/x/@u') as $element) {
    $value = $element->value;
    if (substr($value, -1,1) === '/') {
        $base = $value;
    } else {
        echo $base, $value, "\n";
    }
}

With your example XML document:

male/86644/lol.png
male/86644/haha.png
male/86644/name.png
male/27827/page.png
male/27827/examp.png
male/27827/bottom.png

This example is using the union operator | to obtain all wanted nodes at once.


I was originally looking for doing the following within xpath but is not possible AFAIK. However PHP can take care of this: Run an Xpath expression in context to a previous xpath query nodes:

$array = array_map(function($context) use($xp) {
    return $xp->evaluate('concat(../../@baseurl, .)', $context);
}, iterator_to_array($xp->query('//x/@u')));

Give $array then:

Array
(
    [0] => male/86644/lol.png
    [1] => male/86644/haha.png
    [2] => male/86644/name.png
    [3] => male/27827/page.png
    [4] => male/27827/examp.png
    [5] => male/27827/bottom.png
)

That is probably more straight forward.

If you add an extra element to each child called baseid , and its content to be the parents name like below. . .

<blaah1 name="whatever">
<gender name="male">

<example1 baseurl="male/86644/">
<x u="lol.png" baseid="example1"/>
<x u="haha.png" baseid="example1"/>
<x u="name.png" baseid="example1"/>
</example1>

<example2 baseurl="male/27827/">
<x u="page.png" baseid="example2"/>
<x u="examp.png" baseid="example2"/>
<x u="bottom.png" baseid="example2"/>
</example2>

</gender>
</blaah1>

You could get the parents baseurl and child u with the two xpaths below

$xml_load = simplexml_load_file("myxmlfile.xml");

$x = $xml_load->xpath('//gender[@name="male"]/*/x'); 
foreach($x as $display)
{
$base_url = $xml_load->xpath('//gender[@name="male"]/'.$display["baseid"].''); 
foreach($base_url as $base)
{
echo 'img: '. $base['baseurl'] . $display['u'],'<hr>';
}
}

Finished output . . .

img: male/86644/lol.png
img: male/86644/haha.png
img: male/86644/name.png
img: male/27827/page.png
img: male/27827/examp.png
img: male/27827/bottom.png

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM