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

后端 未结 4 521
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 00:51

The problem seems straightforward, but I\'m having trouble getting access to the tag name of a SimpleXMLElement.

Let\'s say I have the follow XML structure:

4条回答
  •  Happy的楠姐
    2020-12-02 01:51

    Here's what's probably the simplest way to copy a node's children and attributes without using XSLT:

    function clonishNode(DOMNode $oldNode, $newName, $newNS = null)
    {
        if (isset($newNS))
        {
            $newNode = $oldNode->ownerDocument->createElementNS($newNS, $newName);
        }
        else
        {
            $newNode = $oldNode->ownerDocument->createElement($newName);
        }
    
        foreach ($oldNode->attributes as $attr)
        {
            $newNode->appendChild($attr->cloneNode());
        }
    
        foreach ($oldNode->childNodes as $child)
        {
            $newNode->appendChild($child->cloneNode(true));
        }
    
        $oldNode->parentNode->replaceChild($newNode, $oldNode);
    }
    

    Which you can use this way:

    $dom = new DOMDocument;
    $dom->loadXML('xyz');
    
    $oldNode = $dom->getElementsByTagName('bar')->item(0);
    clonishNode($oldNode, 'BXR');
    
    // Same but with a new namespace
    //clonishNode($oldNode, 'newns:BXR', 'http://newns');
    
    die($dom->saveXML());
    

    It will replace the old node with a clone with a new name.

    Attention though, this is a copy of the original node's content. If you had any variable pointing to the old nodes, they are now invalid.

提交回复
热议问题