【问题标题】:Uncaught exception 'DOMException' with message 'Hierarchy Request Error'未捕获的异常“DOMException”和消息“层次请求错误”
【发布时间】:2013-04-26 22:48:43
【问题描述】:

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

必填:

我想把这个改成..

<?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”和消息“层次请求错误”

我的代码是

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

【问题讨论】:

  • 你可以在问题详情中看到xml要求...
  • 当我尝试使用 replaceChild 时出现错误提示“层次请求错误”,我不知道自己在犯什么错误
  • 我只是想要一个节点需要包含在 p 标签中。
  • 是的,下次确定..感谢您的建议..
  • 我恢复了原始 XML 示例,以便更好地理解并与答案对齐。希望你不要介意。

标签: php xml dom xml-parsing


【解决方案1】:

Hierarchy Request Error 和 PHP 中的 DOMDocument 错误意味着您正在尝试将节点移动到自身中。将其与下图中的蛇进行比较:

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

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>

现在一切都很好。

【讨论】:

  • 这正是我想要的。非常感谢您的解释。谢谢
猜你喜欢
  • 2011-07-14
  • 2012-07-12
  • 2023-03-05
  • 1970-01-01
  • 2015-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-03
相关资源
最近更新 更多