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 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?