我有两个
XML树,并希望添加一个树作为另一个树叶.
显然:
- $tree2->addChild('leaf',$tree1);
不起作用,因为它仅复制第一个根节点.
好的,所以我以为我会遍历整个第一棵树,每一个元素逐个添加到第二个树.
但是请考虑这样的XML:
- <root>
- aaa
- <bbb/>
- ccc
- </root>
如何访问“ccc”? tree1> children()只返回“bbb”….
您不能直接使用SimpleXML添加“树”,如您所见.但是,您可以使用某些DOM方法为您提供同样的基础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;