SimpleXML:将一棵树追加到另一棵树

编程入门 行业动态 更新时间:2024-10-14 14:22:48
本文介绍了SimpleXML:将一棵树追加到另一棵树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两棵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:将一棵树追加到另一棵树

本文发布于:2023-11-29 21:02:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647617.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:一棵树   棵树   SimpleXML

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!