0

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

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

输入.xml

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

output.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(); 
    }

?>
4

1 回答 1

1

你得到了,Wrong Document Error因为你在 中创建了一个新DOMDocument对象createInnerSteps(),每次调用它。

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

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

$dom  = new DOMDocument();

$dom = $parent->ownerDocument;

查看运行示例

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

于 2012-09-05T12:58:50.057 回答