1

这是我的 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文档中我似乎甚至找不到一个向我展示如何实现新元素的示例。

createElementand方法只告诉我如何插入元素节点,appendChild而不是如何插入剩余的文件夹子节点。

4

1 回答 1

2

选择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();

在演示中查看结果

于 2017-03-07T13:36:16.140 回答