dongma7796 2012-12-23 19:05
浏览 338
已采纳

通过xpath和所有子元素获取父元素

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?

  • 写回答

2条回答 默认 最新

  • douping7105 2012-12-23 19:17
    关注

    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, "
    ";
        }
    }
    

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作