带有消息'Hierarchy Request Error'的未捕获异常'DOMException'

Cha*_*ori 10 php xml dom xml-parsing

在将节点替换或添加到节点时,我遇到错误.

要求是:

我想把它改成..

<?xml version="1.0"?>
<contacts>
  <person>Adam</person>
  <person>Eva</person>
  <person>John</person>
  <person>Thomas</person>
</contacts>
Run Code Online (Sandbox Code Playgroud)

像这样

<?xml version="1.0"?>
<contacts>
  <person>Adam</person>
  <p>
      <person>Eva</person>
  </p>
  <person>John</person>
  <person>Thomas</person>
</contacts>
Run Code Online (Sandbox Code Playgroud)

错误是

致命错误:未捕获的异常'DOMException',消息'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);
    }
}
Run Code Online (Sandbox Code Playgroud)

hak*_*kre 38

错误层次请求错误DOM文档在PHP意味着你正在尝试一个节点移动到自身.在下图中将其与蛇相比较:

蛇吃自己

与您的节点类似.您将节点移动到自身.这意味着,当您想要用段落替换此人时,该人已经是该段落的子女.

使用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>
Run Code Online (Sandbox Code Playgroud)

伊娃已经走了.它的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>
Run Code Online (Sandbox Code Playgroud)

现在一切都很好.

  • 好答案.谢谢. (3认同)
  • 这正是我想要的..非常非常感谢您的解释..谢谢 (2认同)