gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 02:36:52 24 4
gpt4 key购买 nike

我已经决定没有办法用 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>

最佳答案

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

<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>

如您所见,两个文档的树都保留了下来,只有您描述为相同的节点是根节点(实际上也是两个节点),所以它没有被接管第二个文档,但只有它是子文档。

关于php - 如何轻松地将两个具有相同父节点的 XML 文档合并为一个文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10341556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com