2013-05-02 44 views
7

在將節點替換或添加到節點時出現錯誤。帶有消息「層次結構請求錯誤」的未捕獲異常'DOMException'

需要的是:

我想改變這..

<?xml version="1.0"?> 
<contacts> 
    <person>Adam</person> 
    <person>Eva</person> 
    <person>John</person> 
    <person>Thomas</person> 
</contacts> 

這樣

<?xml version="1.0"?> 
<contacts> 
    <person>Adam</person> 
    <p> 
     <person>Eva</person> 
    </p> 
    <person>John</person> 
    <person>Thomas</person> 
</contacts> 

誤差

Fatal error: Uncaught exception 'DOMException' with message 'Hierarchy Request Error'

我的代碼是

function changeTagName($changeble) { 
    for ($index = 0; $index < count($changeble); $index++) { 
     $new = $xmlDoc->createElement("p"); 
     $new ->setAttribute("channel", "wp.com"); 
     $new ->appendChild($changeble[$index]); 
     $old = $changeble[$index]; 
     $result = $old->parentNode->replaceChild($new , $old); 
    } 
} 
+0

你可以看到xml需求的問題詳細信息... – 2013-05-02 17:51:06

+0

當我嘗試使用replaceChild時出現錯誤說'Hierarchy Request Error'我不明白我在做什麼錯誤 – 2013-05-02 17:55:49

+0

我只想要一個節點是需要的被包含在p標籤多數民衆贊成在它。 – 2013-05-02 17:57:21

回答

36

錯誤層次請求錯誤DOM文檔在PHP意味着你正在嘗試一個節點移動到自身。在下面的圖片蛇比較:

Snake eats itself

類似,這是你的節點。您將節點移動到本身。這意味着,當你想用該段替換該人時,該人已經是該段的孩子。

的appendChild()方法已經有效地移動人DOM樹的,它不屬於任何再:

$para = $doc->createElement("p"); 
$para->setAttribute('attr', 'value'); 
$para->appendChild($person); 

<?xml version="1.0"?> 
<contacts> 
    <person>Adam</person> 

    <person>John</person> 
    <person>Thomas</person> 
</contacts> 

伊娃已經走了。它的parentNode已經是該段落了。

因此,你首先要替換,然後追加孩子:

$para = $doc->createElement("p"); 
$para->setAttribute('attr', 'value'); 
$person = $person->parentNode->replaceChild($para, $person); 
$para->appendChild($person); 

<?xml version="1.0"?> 
<contacts> 
    <person>Adam</person> 
    <p attr="value"><person>Eva</person></p> 
    <person>John</person> 
    <person>Thomas</person> 
</contacts> 

現在一切都很好。

+0

這工作正是我想要的..非常感謝您的好解釋..謝謝 – 2013-05-02 18:54:24

+2

好的答案。謝謝。 – 2014-07-09 07:27:32

相關問題