douding6266 2017-01-16 17:09
浏览 195
已采纳

使用DOMXPath用XPath表达式替换foreach循环

I want to replace a foreach loop using a xpath expression, but I need that a DOMXPath object to return more than one list.

I have the following XML (simplified) and I using DOMDocument and DOMXPath to iterate over it:

<a:RoomsType>
    <a:Rooms>
      <a:Room>
          <a:RPH>0</a:RPH>
      </a:Room>
      <a:Room>
          <a:RPH>1</a:RPH>
      </a:Room>
      <a:Room>
          <a:RPH>2</a:RPH>
      </a:Room>
      <a:Room>
          <a:RPH>0</a:RPH>
      </a:Room>
    <a:Rooms>
<a:RoomsType>

I want to split the rooms by the RPH number, creating a list of rooms for each RPH number. Currently, I'm using the following code:

 //$xpath is a DOMXPath object
 $roomsToIterate = $this->xpath->query("//a:RoomsType/a:Rooms/a:Room");

 $roomList = array();
 foreach ($roomsToIterate as $room) {
     $rphCandidate = $room->getElementsByTagName("RPH")->item(0)->nodeValue;
     if (!isset($roomList[$rphCandidate])) {
         $roomList[$rphCandidate] = array();
     }
     $roomList[$rphCandidate][] = $room;
 }

This is working for now, but I want to replace the foreach loop with a Xpath expression. I can use the expression $rooms = $this->xpath->query("//a:RoomsType/a:Rooms/a:Room[a:RPH='{$rph}']"); with $rph being a number, but how can I do it if I don't know the RPH (it could be anything between 0 and 99). Is it possible?

In short, Are there any way to replace my foreach loop using XPath?

I was thinking about the use of registerPhpFunctions and a custom function, but I concerned about the performance of this approach compared with foreach loop

  • 写回答

1条回答 默认 最新

  • dongpou1935 2017-01-17 14:49
    关注

    Xpath 1.0 expression will return a list of nodes, they can to some extend flatten an existing structure if you use an axis like descendant or ancestor, but it will be a list of nodes. It can not group or aggregate them.

    You could fetch a lists of nodes with a specific RPH value. But you would need to this for each value, the result would be another loop. This would mean to fetch all RPH values, make them unique, iterate them and execute and Xpath expression for each value.

    Your current solution is fine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记