douqiang6448 2016-10-19 19:24
浏览 12
已采纳

根据php中父节点的属性将子句附加到xml

I would like to ask, how to easily append new node to the end of found node in php. Lets say I have xml like this:

<Root>
    <child id=1>
        <text>smth</text>
    </child>
</Root>

I want to find the child element with id 1 and then append another node as last. I was trying to find an answer, but it either answer how to find it, or how to write into it, unfortunately I was not able to put it together.

I would be really happy if someone can help me with this.

  • 写回答

2条回答 默认 最新

  • dongshiqin1352 2016-10-19 19:48
    关注

    You can use the xpath to find the relevant node (based on the id) and then use the addChild to add new child-node to the node you just found:

    $str =<<< END
    <Root>
        <child id="1">
            <text>smth</text>
        </child>
    </Root>
    END;
    
    $result = simplexml_load_string($str);
    
    $child = $result->xpath("*[@id='1']")[0];
    $child->addChild('text', 'node value');
    
    // The part from here is only to make the output pretty-xml
    // instead you can just use $result->saveXML()
    $dom = new DOMDocument("1.0");
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML($result->saveXML());
    var_dump($dom->saveXML());
    

    The output will be:

    string(115) "<?xml version="1.0"?>
    <Root>
        <child id="1">
            <text>smth</text>
            <text>node value</text>
        </child>
    </Root>
    "
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型