如何轻松地将具有相同父节点的两个XML文档合并为一个文档


How can I easily combine two XML documents with the same parent node into one document?

>我已经决定没有办法用SimpleXMLElements做到这一点。我一直在阅读PHP DOMDocument手册,我认为我可以通过迭代来完成,但这似乎效率低下。有没有更好的方法不会发生在我身上?

伪代码式迭代解决方案:

// two DOMDocuments with same root element
$parent = new ...
$otherParent = new ...
$children = $parent->getElementByTagName('child');
foreach ($children as $child) {
   $otherParent->appendChild($child);
}

为清楚起见,我有两个 XML 文档,它们都如下所示:

    <parent>
      <child>
        <childOfChild>
           {etc, more levels of nested XML trees possible}
        </childOfChild>
      </child>
      <child>
        <childOfChild>
           {etc, more levels possible}
        </childOfChild>
      </child>
</parent>

我想要这样的输出:

<parent>
  {all children of both original XML docs, order unimportant, that preserves any nested XML trees the children may have}
<parent>

如果我精确而严格地回答您的问题,您可以在两个文件之间识别的唯一公共节点将是根节点,因此解决方案将是:

<doc1:parent>
    <doc1:children>...</>
    <doc2:children>...</>
</doc1:parent>

写的顺序并不重要,所以正如你在这里看到的,doc2 在 doc1 之后。包含上述示例 XML 表单的两个 SimpleXML 元素的示例代码$xml1$xml2

$doc1 = dom_import_simplexml($xml1)->ownerDocument;
foreach (dom_import_simplexml($xml2)->childNodes as $child) {
    $child = $doc1->importNode($child, TRUE);
    echo $doc1->saveXML($child), "'n";
    $doc1->documentElement->appendChild($child);
}

现在$doc1包含由以下 XML 表示的文档:

<?xml version="1.0"?>
<parent>
      <child>
        <childOfChild>
           {etc, more levels of nested XML trees possible}
        </childOfChild>
      </child>
      <child>
        <childOfChild>
           {etc, more levels possible}
        </childOfChild>
      </child>
      <child>
        <childOfChild>
           {etc, more levels of nested XML trees possible}
        </childOfChild>
      </child>
      <child>
        <childOfChild>
           {etc, more levels possible}
        </childOfChild>
      </child>
</parent>

如您所见,两个文档的树都被保留了,只有您描述为相同的节点是根节点(实际上也是两个节点),因此它不会从第二个文档接管,而只是从子节点接管。