使用DOMDocument将新节点及其子节点添加到XML文档

时间:2017-03-07 12:41:40

标签: php xml domdocument appendchild clonenode

这是我的XML文档示例,其中显示了网站站点地图

<?xml version="1.0" encoding="UTF-8"?>
<project name="Esurance 365 Portal">
    <elements>
        <element name="folderone" path="forms/folderone">
            <folder function="model">models</folder>
            <folder function="controller">controllers</folder>
            <folder function="view">views</folder>
        </element>
    </elements>
</project>

我想使用DOMDocument在图示的节点之上添加另一个元素节点,使其显示如下

<?xml version="1.0" encoding="UTF-8"?>
    <project name="Esurance 365 Portal">
        <elements>
           <element name="foldertwo" path="forms/foldertwo">
                <folder function="model">modelstwo</folder>
                <folder function="controller">controllerstwo</folder>
                <folder function="view">viewstwo</folder>
            </element>
            <element name="folderone" path="forms/folderone">
                <folder function="model">models</folder>
                <folder function="controller">controllers</folder>
                <folder function="view">views</folder>
            </element>
        </elements>
    </project>

但是从DOMDocument文档中我似乎找不到一个例子来向我展示如何实现新元素。

createElementappendChild方法只显示如何插入元素节点,但不显示如何插入剩余的文件夹子节点。

1 个答案:

答案 0 :(得分:1)

选择element代码并使用cloneNode()进行复制。使用setAttribute()设置属性的新值并使用nodeValue在目标标记中设置新文本。在代码末尾,使用insertBefore()在现有元素之前插入新元素。

$dom = new DOMDocument();
$dom->loadXml($xml);
// select "element" tag and copy it
$element = $dom->getElementsByTagName("element")->item(0);
$clone = $element->cloneNode(true);
// change value of attribute 
$clone->setAttribute("name", "foldertwo");
$clone->setAttribute("path", "forms/foldertwo");
// select "folder" tag in new "element" tag change text of them
$folder = $clone->getElementsByTagName("folder");
$folder->item(0)->nodeValue = "modelstwo";
$folder->item(1)->nodeValue = "controllerstwo";
$folder->item(2)->nodeValue = "viewstwo";
// insert new elements before existing element.
$element->parentNode->insertBefore($clone, $element);
$xml = $dom->saveXml();

请参阅demo

中的结果