如何通过DOM对象在SimpleXML中重命名标签? [英] How do you rename a tag in SimpleXML through a DOM object?

查看:147
本文介绍了如何通过DOM对象在SimpleXML中重命名标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题似乎很简单,但是我无法访问SimpleXMLElement的标签名称。

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

假设我有以下XML结构: p>

Let's say I have the follow XML structure:

<xml>
     <oldName>Stuff</oldName>
</xml>

我想要这样:

<xml>
     <newName>Stuff</newName>
</xml>

是否可以不做整个对象的副本?

我已经开始意识到我遇到这个问题的方式的错误。看来我需要将我的SimpleXMLElement转换成一个DOM对象。在这样做的时候,我发现很难按照我想要的方式来处理对象(显然,重新命名DOM中的标签不容易,因为某个原因)。

I've started to realize the errors of the ways I am approaching this problem. It seems that I need to convert my SimpleXMLElement into a DOM object. Upon doing so I find it very hard to manipulate the object in the way I want (apparently renaming tags in a DOM isn't easy to do for a reason).

所以...我可以使用导入将我的SimpleXMLElement导入DOM对象,但是我发现很难做到这个克隆。

So... I am able to import my SimpleXMLElement into a DOM object with the import, but I am finding it difficult to do the clone.

以下是克隆DOM对象背后的正确思路,或者我还有待解决:

Is the following the right thinking behind cloning a DOM object or am I still way off:

$old = $dom->getElementsByTagName('old')->item(0); // The tag is unique in my case
$new = $dom->createElement('new');

/* ... some recursive logic to copy attributes and children of the $old node ... */

$old->ownerDocument->appendChild($new);
$new->ownerDocument->removeChild($old);


推荐答案

这可能是复制节点的孩子的最简单的方法和属性,而不使用XSLT:

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);
}

您可以使用以下方式:

$dom = new DOMDocument;
$dom->loadXML('<foo><bar x="1" y="2">x<baz/>y<quux/>z</bar></foo>');

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

这篇关于如何通过DOM对象在SimpleXML中重命名标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆