SimpleXML如何在节点中添加子级? [英] SimpleXML how to prepend a child in a node?

查看:67
本文介绍了SimpleXML如何在节点中添加子级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我打电话

addChild('actor', 'John Doe');

这个孩子被添加到最后.有没有办法让这个新孩子成为第一个孩子?

this child is added in the last. Is there a way to make this new child a first child?

推荐答案

如前所述,SimpleXML不支持该功能,因此您必须使用DOM.我的建议是:用您需要在程序中使用的任何东西扩展SimpleXMLElement.这样,您可以将所有DOM操作和其他XML魔术保留在实际程序之外.通过将这两个问题分开,可以提高可读性和可维护性.

As it's been mentionned, SimpleXML doesn't support that so you'd have to use DOM. Here's what I recommend: extend SimpleXMLElement with whatever you need to use in your programs. This way, you can keep all the DOM manipulation and other XML magic outside of your actual program. By keeping the two matters separate, you improve readability and maintainability.

以下是使用新方法prependChild()扩展SimpleXMLElement的方法:

Here's how to extend SimpleXMLElement with a new method prependChild():

class my_node extends SimpleXMLElement
{
    public function prependChild($name, $value)
    {
        $dom = dom_import_simplexml($this);

        $new = $dom->insertBefore(
            $dom->ownerDocument->createElement($name, $value),
            $dom->firstChild
        );

        return simplexml_import_dom($new, get_class($this));
    }
}

$actors = simplexml_load_string(
    '<actors>
        <actor>Al Pacino</actor>
        <actor>Zsa Zsa Gabor</actor>
    </actors>',
    'my_node'
);

$actors->addChild('actor', 'John Doe - last');
$actors->prependChild('actor', 'John Doe - first');

die($actors->asXML());

这篇关于SimpleXML如何在节点中添加子级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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