在 domdocument 中创建 XML 片段并添加到其父级


Creating XML Fragment in domdocument and adding to its parent

下面是我用来创建一堆xml节点并尝试附加到传递给它的父节点的代码段。

不确定出了什么问题,父节点没有得到增强。

输入.xml

<?xml version="1.0"?>
<root>
    <steps> This is a step </steps>
    <steps> This is also a step </steps>
</root>

输出.xml应为

<?xml version="1.0">
<root>
    <steps>
        <step>
            <step_number>1</step_number>
            <step_detail>Step detail goes here</step_detail>
        </step> 
    </steps>
    <steps>
        <step>
            <step_number>2</step_number>
            <step_detail>Step detail of the 2nd step</step_detail>
        </step> 
    </steps>
</root>

    <?php
    $xml = simplexml_load_file( 'input.xml' );
    $domxml  = dom_import_simplexml( $xml );
    //Iterating through all the STEPS node
    foreach ($steps as $stp ){
        createInnerSteps( &$stp, $stp->nodeValue , 'Expected Result STring' );
        echo 'NODE VAL  :-----' . $stp->nodeValue;// Here it should have the new nodes, but it is not
    }
    function createInnerSteps( &$parent )
    {   
        $dom  = new DOMDocument();
        // Create Fragment, where all the inner childs gets appended
        $frag = $dom->createDocumentFragment();
        // Create Step Node
        $stepElm = $dom->createElement('step');
        $frag->appendChild( $stepElm );
        // Create Step_Number Node and CDATA Section
        $stepNumElm = $dom->createElement('step_number');
        $cdata = $dom->createCDATASection('1');
        $stepNumElm->appendChild ($cdata );
        // Append Step_number to Step Node
        $stepElm->appendChild( $stepNumElm );
        // Create step_details and append to Step Node 
        $step_details = $dom->createElement('step_details');
        $cdata = $dom->createCDATASection('Details');
        $step_details->appendChild( $cdata );
        // Append step_details to step Node
        $stepElm->appendChild( $step_details );
        // Add Parent Node to step element
            //  I get error PHP Fatal error:  
            //  Uncaught exception 'DOMException' with message 'Wrong Document Error'
        $parent->appendChild( $frag );
        //echo 'PARENT : ' .$parent->saveXML(); 
    }
?>

您获得Wrong Document Error,因为每次调用它时,您都会在createInnerSteps()中创建一个新的DOMDocument对象。

当代码到达行$parent->appendChild($frag)时,$frag属于在函数中创建的文档,$parent属于您尝试操作的主文档。 您不能像这样在文档之间移动节点(或片段(。

最简单的解决方案是通过替换来仅使用一个文档:

$dom  = new DOMDocument();

$dom = $parent->ownerDocument;

请参阅运行示例。

最后,要获得所需的输出,您需要删除每个 <steps> 元素中的现有文本。