问题
I've decided there's no way to do this with SimpleXMLElements. I have been reading the PHP DOMDocument manual, and I think I could do it with iteration, but that seems inefficient. Is there a better way that's not occurring to me?
Psuedocode-ish iterative solution:
// two DOMDocuments with same root element
$parent = new ...
$otherParent = new ...
$children = $parent->getElementByTagName('child');
foreach ($children as $child) {
$otherParent->appendChild($child);
}
For clarity, I have two XML documents that both look like this:
<parent>
<child>
<childOfChild>
{etc, more levels of nested XML trees possible}
</childOfChild>
</child>
<child>
<childOfChild>
{etc, more levels possible}
</childOfChild>
</child>
</parent>
And I would like output like this:
<parent>
{all children of both original XML docs, order unimportant, that preserves any nested XML trees the children may have}
<parent>
回答1:
As the only common node you could identify between the two files would be the root node if I take your question precisely and strict so the solution would be:
<doc1:parent>
<doc1:children>...</>
<doc2:children>...</>
</doc1:parent>
You wrote the order is not important, so as you can see here, doc2 comes after doc1. Example code for two SimpleXML elements $xml1
and $xml2
that contain both the example XML form above:
$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);
}
Now $doc1
contains the document represented by this 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>
As you can see, the trees of both documents are preserved, only the node you describe as same is the root node (actually that are two nodes, too), so it's not taken over from the second document, but only it's children.
来源:https://stackoverflow.com/questions/10341556/how-can-i-easily-combine-two-xml-documents-with-the-same-parent-node-into-one-do