问题描述
我有两棵XML树,想将一棵树作为叶子添加到另一棵树上.
I have two XML trees and would like to add one tree as a leaf to the other one.
显然:
$tree2->addChild('leaf', $tree1);
不起作用,因为它仅复制第一个根节点.
doesn't work, as it copies only the first root node.
好的,所以我想我要遍历整个第一棵树,将每个元素一个接一个地添加到第二棵树上.
Ok, so then I thought I would traverse the whole first tree, adding every element one by one to the second one.
但是考虑这样的XML:
But consider XML like this:
<root>
aaa
<bbb/>
ccc
</root>
如何访问抄送"? tree1->children()
仅返回"bbb"....
How do I access "ccc"? tree1->children()
returns just "bbb"... .
推荐答案
如您所见,您不能直接使用SimpleXML添加树".但是,您可以使用某些DOM方法为您完成繁重的工作,同时仍在处理相同的基础XML.
You can't add a "tree" directly using SimpleXML, as you have seen. However, you can use some DOM methods to do the heavy lifting for you whilst still working on the same underlying XML.
$xmldict = new SimpleXMLElement('<dictionary><a/><b/><c/></dictionary>');
$kitty = new SimpleXMLElement('<cat><sound>meow</sound><texture>fuzzy</texture></cat>');
// Create new DOMElements from the two SimpleXMLElements
$domdict = dom_import_simplexml($xmldict->c);
$domcat = dom_import_simplexml($kitty);
// Import the <cat> into the dictionary document
$domcat = $domdict->ownerDocument->importNode($domcat, TRUE);
// Append the <cat> to <c> in the dictionary
$domdict->appendChild($domcat);
// We can still use SimpleXML! (meow)
echo $xmldict->c->cat->sound;
这篇关于SimpleXML:将一棵树追加到另一棵树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!