How do I create a duplicate of an XML element, but change the name of the element and delete the original? [duplicate]

久未见 提交于 2020-01-03 04:35:21

问题


Possible Duplicate:
How do you rename a tag in SimpleXML through a DOM object?

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>

What strategy would I use, to do so in SimpleXML?


回答1:


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.

Edit: 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.

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.)



来源:https://stackoverflow.com/questions/6921697/how-do-i-create-a-duplicate-of-an-xml-element-but-change-the-name-of-the-elemen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!