douxuan4556 2015-11-17 20:13
浏览 43
已采纳

PHP中的XML克隆节点

I have to clone an XML node and its childs and append it to a new XML in a specifics tag.

Ie:

Source XML:

<root>
  <element>
    <back>
    <item1>ABC</item1>
    <item2>DEF</item2>
    <more>
      <moreitem>GHI</moreitem>
    </more
    </back>
  </element>
</root>

Destination XML:

<root>
  <base1>
    <item1>FOO</item1>
    <item2>BAR</item2>
  <base2>
    **<back>From source XML and all its childs here</back>**
  </base2>
  </base1>
<root>
  • 写回答

3条回答 默认 最新

  • duanping5306 2015-11-17 20:29
    关注

    DOMXpath::evaluate() allows you to fetch nodes using Xpath expressions. DOMDocument::importNode() duplicates a node and imports a node into a target document. DOMNode::cloneNode() create a duplicate of node to add in the same document. DOMNode::appendChild() allows you to append the imported/cloned node.

    $source = <<<'XML'
    <root>
      <element>
        <back>
        <item1>ABC</item1>
        <item2>DEF</item2>
        <more>
          <moreitem>GHI</moreitem>
        </more>
        </back>
      </element>
    </root>
    XML;
    
    $target = <<<'XML'
    <root>
      <base1>
        <item1>FOO</item1>
        <item2>BAR</item2>
        <base2>
        </base2>
      </base1>
    </root>
    XML;
    
    $sourceDocument = new DOMDocument();
    $sourceDocument->loadXml($source);
    $sourceXpath = new DOMXpath($sourceDocument);
    
    $targetDocument = new DOMDocument();
    $targetDocument->loadXml($target);
    $targetXpath = new DOMXpath($targetDocument);
    
    foreach ($targetXpath->evaluate('/root/base1/base2[1]') as $targetNode) {
      foreach ($sourceXpath->evaluate('/root/element/back') as $backNode) {
        $targetNode->appendChild($targetDocument->importNode($backNode, TRUE));
      }
    }
    
    echo $targetDocument->saveXml();
    

    Output:

    <?xml version="1.0"?>
    <root>
      <base1>
        <item1>FOO</item1>
        <item2>BAR</item2>
        <base2>
          <back>
            <item1>ABC</item1>
            <item2>DEF</item2>
            <more>
              <moreitem>GHI</moreitem>
            </more>
          </back>
        </base2>
      </base1>
    </root>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?