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

通过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 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?