如何创建 XML 元素的副本,但更改元素的名称并删除原始元素? [英] How do I create a duplicate of an XML element, but change the name of the element and delete the original?
问题描述
可能的重复:
如何在 SimpleXML 中重命名标签通过 DOM 对象?
如果我有这样的 XML 文档:
If I have an XML document like this:
<document>
<dogs>
<bulldog>Blu</bulldog>
<terrier>Benjie</terrier>
</dogs>
<cats>
<tiger>Tiggger</tiger>
<lion>Cowardly</lion>
</cats>
</document>
而且我想转载,添加一些属性,但不保留原....
And I want to reprint it, adding some attributes, but not keep the original....
<document>
<canine type="fiction">
<bulldog>Blu</bulldog>
<terrier>Benjie</terrier>
</canine>
<feline type="fiction">
<tiger>Tiggger</tiger>
<lion>Cowardly</lion>
</feline>
</document>
在 SimpleXML 中我会使用什么策略?
What strategy would I use, to do so in SimpleXML?
推荐答案
我认为您需要对数据进行深拷贝,擦除
元素,创建一个新的
元素,然后附加之前的深层副本.
I think you will need to make a deep copy of the data, erase the <dogs>
element, create a new <canine>
element, and then append the deep copy from earlier.
虽然您可以使用 $copy = clone $sxml->dogs;
进行克隆,然后执行 unset($sxml->dogs);
,实际的递归添加很痛苦,您可能需要编写自己的递归内容.PHP.net 评论中有一些示例.
While you can make clones with $copy = clone $sxml->dogs;
and then do unset($sxml->dogs);
, the actual recursive-adding is a pain and you may need to code your own recursive stuff. There are some examples in the PHP.net comments.
如果事情变得更复杂,您可能还需要考虑使用 DOM.(您可以使用 SimpleXML 并将 到 和
If things get more complex, you might also want to consider DOM instead. (You can take SimpleXML and convert to and from DOM if necessary.)
这篇关于如何创建 XML 元素的副本,但更改元素的名称并删除原始元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!