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条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog