PHP DOMElement appendChild 获取 DOMException Wrong Document 错误

PHP DOMElement appendChild get DOMException Wrong Document Error

我想将 XML 文档中的 <w:p> 标签复制到另一个文档中。两个 XML 文档都遵循以下结构:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:main=""here is some namespace definitions">
  <w:body>
    <w:p>
       <somechildelementshere />
    </w:p>
  </w:body>
</w:document>

我有这个 PHP 代码:

// $targetDocument contains a <w:document> tag with their children
$target_body = $targetDocument->getElementsByTagNameNS($ns, 'body')[0];

// $sourceBody contains a <w:body> tag with their children
$paragraphs = $sourceBody->getElementsByTagNameNS($ns, 'p');

// $target_body is a DOMElement and $paragraph will be a DOMElement too
foreach ($paragraphs as $paragraph) {
  $target_body->importNode($paragraph, true);
}

然后在 foreach 中我收到 DOMException Wrong Document Error 消息。

如何将一个 DOMElement 作为子元素添加到另一个 DOMElement 中?

XML 文档和代码存在一些问题。开发时最好确保您获得代码以显示生成的任何错误,因为这有助于调试。

我已将文档中的命名空间更改为 w 以匹配实际使用的命名空间,我还删除了 xmlns:main=""here 中的额外引号并放入了一个虚拟 URL.

对于代码,您必须对要添加代码的文档而不是元素调用 importNode()。请注意,这也只会使节点可用,而不会实际插入它。这里我把新建的节点暂存起来,传给目标文档中我要添加节点的节点上appendChild()

工作代码是(为了简单起见,我只使用相同的文档作为源和目标)...

$source = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:w="http://some.url">
  <w:body>
    <w:p>
       <somechildelementshere />
    </w:p>
  </w:body>
</w:document>';

$targetDocument = new DOMDocument();
$targetDocument->loadXML($source);
$sourceBody = new DOMDocument();
$sourceBody->loadXML($source);
$ns = "http://some.url";

$target_body = $targetDocument->getElementsByTagNameNS($ns, 'body')[0];

// $sourceBody contains a <w:body> tag with their children
$paragraphs = $sourceBody->getElementsByTagNameNS($ns, 'p');

// $target_body is a DOMElement and $paragraph will be a DOMElement too
foreach ($paragraphs as $paragraph) {
    $impParagraph = $targetDocument->importNode($paragraph, true);
    $target_body->appendChild($impParagraph);
}

echo $targetDocument->saveXML();