How do I create a duplicate of an XML element, but

2019-06-11 17:34发布

问题:

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