【问题标题】:both appendChild and insertBefore when called on DOMDocument append node after rootappendChild 和 insertBefore 在 DOMDocument 上调用时都在 root 之后追加节点
【发布时间】:2012-06-11 06:56:38
【问题描述】:

我有一个函数可以将一个无值元素和一堆带值的子元素添加到一个 xml 文件中,所以我写它来接受两个参数 $tag(String the parent node) 和 $hash(Array $elm=> $elm_value)

function addUser($tag, $hash)
    {
        $dom = new DOMDocuemnt();
        $dom->preserveWhiteSpace = false;
        $dom->formatOutput = true;
        $dom->load('file');

        $parent = $dom->createElement($tag);
        foreach($hash as $elm => $value){
            $n = $dom->createElement($elm, $value);
            $parent->appendChild($n);
        }
        $dom->appendChild($parent);

        $dom->save('file');
        return $dom->saveXML();
    }

唯一的问题是$dom->appendChild($parent) 在根元素的结束标记之后附加所有内容,从而弄乱了我的 xml 文件。所以我尝试了$dom->insertBefore($parent),结果相同。所以我尝试了$xpath = new DOMXPath($dom); $root = $xpath->query('/')->item(0); $root->appendChild($parent);。结果相同。然后我尝试使用$dom->getElementsByTagName(name of root)->item(0); 选择根元素,当它真正起作用时我感到很惊讶!但是如果我不知道标签名称怎么办?是否有另一种选择根元素的方法,以便调用 appendChild 或 inserBefore 将元素添加到根结束标记之前而不是之后?

【问题讨论】:

    标签: php xml domdocument appendchild


    【解决方案1】:

    这似乎有效:

    初始 XML 文件 -

    <!-- test.xml -->
    <?xml version="1.0" encoding="UTF-8"?>
    <root>
        <node Id="1">
            <Clicks>click1</Clicks>
        </node>
    </root>
    

    PHP -

    <?php
    
    function addUser($tag, $hash) {
        $dom = new DOMDocument('1.0');
        $dom->preserveWhiteSpace = false;
        $dom->formatOutput = true;
        $dom->load('test.xml');
    
        $parent = $dom->createElement($tag);
        $dom->documentElement->appendChild($parent);
        foreach($hash as $elm => $value){
            $n = $dom->createElement($elm);
            $n->appendChild( $dom->createTextNode( $value ) );
            $parent->appendChild($n);
        }
    
        $dom->save('test.xml');
    }
    
    $arr = array( 'name' => 'pushpesh', 'age' => 30, 'profession' => 'SO bugger' );
    addUser('user', $arr);
    

    XML 文件现在是 -

    <!-- test.xml -->
    <?xml version="1.0" encoding="UTF-8"?>
    <root>
      <node Id="1">
        <Clicks>click1</Clicks>
      </node>
      <user>
        <name>pushpesh</name>
        <age>30</age>
        <profession>SO bugger</profession>
      </user>
    </root>
    

    希望这会有所帮助。

    【讨论】:

    • 太棒了! documentElement 属性起到了作用。有时,以错误的方式工作是您可能犯的最严重的错误。谢谢你让我直截了当!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    相关资源
    最近更新 更多