dov11020 2014-11-20 06:54
浏览 91
已采纳

如何通过php dom在xml上的特定节点中添加新节点

I want to insert new node to specific node but I have no idea how to do it

number.xml

<numbers>
   <number>1</number>
   <number>2</number>
   <number>3</number>
   <number>4</number>
   <number>5</number>
</numbers>

number.php

<?php
$xml = new DOMDocument();
$xml->formatOutput=true;
$xml -> load('number.xml');
$xml_subnumber = $xml->createElement("subNumber");
$xml_subnumber_text = $xml->createTextNode("3.3");
$xml_subnumber->appendChild($xml_subnumber_text);
//something here (I have no idea.)
$xml->save("number.xml") or die("Error");
?>

and I want the xml file seem like this...

<numbers>
   <number>1</number>
   <number>2</number>
   <number>3
     <subNumber>3.3</subNumber>
   </number>
   <number>4</number>
   <number>5</number>
</numbers>
  • 写回答

1条回答 默认 最新

  • douluan5444 2014-11-20 13:57
    关注

    You need to find the number element node and append the new node to it. Here is XPath for that. /numbers/number[3] will return the third number element node. It will return it in a list, because expressions could return several nodes or no nodes. This way the result type always stays the same.

    $xml = new DOMDocument();
    $xml->formatOutput = true;
    $xml->preserveWhiteSpace = false;
    
    $xml->loadXml(
      '<numbers>
       <number>1</number>
       <number>2</number>
       <number>3</number>
       <number>4</number>
       <number>5</number>
      </numbers>'
    );
    $xpath = new DOMXpath($xml);
    
    foreach ($xpath->evaluate('/numbers/number[3]') as $thirdNumber) {
      $subNumber = $thirdNumber->appendChild(
         $xml->createElement("subNumber")
      );
      $subNumber->appendChild($xml->createTextNode("3.3"));
    }
    
    echo $xml->saveXml();
    

    Output:

    <?xml version="1.0"?>
    <numbers>
       <number>1</number>
       <number>2</number>
       <number>3<subNumber>3.3</subNumber></number>
       <number>4</number>
       <number>5</number>
    </numbers>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 依据报错在原代吗格式的基础上解决问题
  • ¥15 在虚拟机中安装flash code
  • ¥15 单片机stm32f10x编写光敏电阻调节3.3伏大功率灯亮度(光强越大灯越暗,白天正常光强灯不亮,使用ADC,PWM等模块)望各位找一下错误或者提供一个可实现功能的代码
  • ¥20 verilog状态机方法流水灯
  • ¥15 pandas代码实现不了意图
  • ¥15 GD32H7 从存储器到外设SPI传输数据无法重复启用DMA
  • ¥25 LT码在高斯信道下的误码率仿真
  • ¥45 渲染完成之后将物体的材质贴图改变,自动化进行这个操作
  • ¥15 yolov5目标检测并显示目标出现的时间或视频帧
  • ¥15 电视版的优酷可以设置电影连续播放吗?