首页 > 解决方案 > PHP DOMElement appendChild get DOMException Wrong Document Error

问题描述

我想将<w:p>XML 文档中的标签复制到另一个文档中。两个 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 作为子元素添加到另一个中?

标签: phpxmlxml-parsingdomdocument

解决方案


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

推荐阅读