2012-09-05 20 views
0

下面是我用來創建一堆xml節點並嘗試附加到傳遞給它的父代的一段代碼。在domdocument中創建XML片段並添加到它的父代

不知道是怎麼回事,父節點沒有得到增強。

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

?> 

回答

1

你所得到的Wrong Document Error因爲您在createInnerSteps()創建一個新的DOMDocument對象,每次調用時間。

當代碼到達$parent->appendChild($frag)行時,$frag屬於在該函數中創建的文檔,而$parent屬於您正在嘗試操作的主文檔。您不能像這樣在文檔之間移動節點(或片段)。

最簡單的解決方法是更換永遠只使用一個文件:

$dom = new DOMDocument(); 

$dom = $parent->ownerDocument; 

a running example

最後,要獲得您想要的輸出,您需要刪除每個<steps>元素中的現有文本。

+0

非常感謝:) – nepsdotin

相關問題