drqvsx1228 2014-05-02 12:37 采纳率: 0%
浏览 39
已采纳

使用php中的DOMDocument从xml获取最后一个子节点

Here is my xml:

<details> 
        <car>
          <id>61XZB6</id>
          <Jan-01-14>20</Jan-01-14>
          <Jan-02-14>435</Jan-02-14>
          <Jan-03-14>454</Jan-03-14>
          <Jan-04-14>768</Jan-04-14>
          <Jan-05-14>24</Jan-05-14>
          <Jan-06-14>675</Jan-06-14>
          <Jan-07-14>213</Jan-07-14>
          <Jan-08-14>44</Jan-08-14>
          <Jan-09-14>565</Jan-09-14>
          <Jan-10-14>80</Jan-10-14>
          <Jan-11-14>998</Jan-11-14>
          <Jan-12-14>67</Jan-12-14>
          <Jan-13-14>77</Jan-13-14>
          <Jan-14-14>909</Jan-14-14>
          <Jan-15-14>34</Jan-15-14>
          <Jan-16-14>887</Jan-16-14>
          <Jan-17-14>767</Jan-17-14>
          <Jan-18-14>545</Jan-18-14>
          <Jan-19-14>67</Jan-19-14>
          <Jan-20-14>787</Jan-20-14>
          <Jan-21-14>898</Jan-21-14>
          <Jan-22-14>435</Jan-22-14>
          <Jan-23-14>42</Jan-23-14>
          <Jan-24-14>232</Jan-24-14>
          <Jan-25-14>234</Jan-25-14>
          <Jan-26-14>675</Jan-26-14>
          <Jan-27-14>46</Jan-27-14>
          <Jan-28-14>546</Jan-28-14>
          <Jan-29-14>88</Jan-29-14>
          <Jan-30-14>0</Jan-30-14>
          <Jan-31-14>0</Jan-31-14>
        </car>
     </details>

My query is how to check the last node inside each tag before inserting a new node to each tag.Thanks in advance for any sort of help extended.

  • 写回答

1条回答 默认 最新

  • dongnan4571 2014-05-02 13:51
    关注

    If I understand you correctly you would like to check for the last element in each car element node? Well, Xpath hast two methods position() and last() that can be used in a condition.

    Select the car nodes

    /details/car

    Select the child element nodes of the car nodes

    /details/car/*

    Add a condition to limit the selection to the last node

    /details/car/*[last()]

    Full example: https://eval.in/145531

    $dom = new DOMDocument();
    $dom->loadXml($xml);
    $xpath = new DOMXpath($dom);
    
    foreach ($xpath->evaluate('/details/car/*[last()]') as $node) {
      var_dump(
        $node->nodeName,
        $node->nodeValue
      );
    }
    

    Output:

    string(9) "Jan-31-14"
    string(1) "0"
    

    HINT!

    Flexible element names are really bad style, you will not be able to define them in a schema. If possible I suggest you change them to something like <amount date="Jan-31-14">0</amount>

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

报告相同问题?

悬赏问题

  • ¥15 关于#stm32#的问题:寻找一块开发版,作为智能化割草机的控制模块和树莓派主板相连,要求:最低可控制 3 个电机(两个驱动电机,1 个割草电机),其次可以与树莓派主板相连电机照片如下:
  • ¥15 Mac(标签-IDE|关键词-File) idea
  • ¥15 潜在扩散模型的Unet特征提取
  • ¥15 iscsi服务无法访问,如何解决?
  • ¥15 感应式传感器制作的感应式讯响器
  • ¥15 如何使用SC92F8003固件库解析私有协议数据?
  • ¥15 如何在音频中嵌入字符串(水印)信息进行传递
  • ¥30 plc怎么以设计说明书申请软著
  • ¥15 硬盘识别不了,需要初始化,可我的数据怎么办
  • ¥15 lvm2被mask了,怎么unmask都没用(标签-ubuntu|关键词-apt)