未捕获的异常“DOMException"和消息“层次请求错误"

2022-01-10 00:00:00 xml xml-parsing dom php

在将子节点替换或添加到节点时出错.

I'm getting error while replacing or adding a child into a node.

必填:

我想把这个改成..

<?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>

错误是

致命错误:未捕获的异常DOMException"和消息层次请求错误"

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);
    }
}

推荐答案

PHP 中的 Hierarchy Request Error with DOMDocument 表示您正在尝试将节点移动到本身.将其与下图中的蛇进行比较:

The error Hierarchy Request Error with DOMDocument in PHP means that you are trying to move a node into itself. Compare this with the snake in the following picture:

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

Similar this is with your node. You move the node into itself. That means, the moment you want to replace the person with the paragraph, the person is already a children of the paragraph.

appendChild() 方法已经有效地将人移出 DOM 树,它不再是一部分:

The appendChild() method effectively already moves the person out of the DOM tree, it is not part any longer:

$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 已经是段落了.

Eva is already gone. Its parentNode is the paragraph already.

因此,您首先要替换然后附加孩子:

So Instead you first want to replace and then append the child:

$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>

现在一切都很好.

相关文章