【问题标题】:PHP DOMElement appendChild get DOMException Wrong Document ErrorPHP DOMElement appendChild get DOMException Wrong Document Error
【发布时间】:2019-09-12 10:36:39
【问题描述】:

我想将一个 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 作为子元素添加到另一个元素中?

【问题讨论】:

  • importNodeDOMDocument 的一种方法,但您正试图在单个元素节点上使用它……

标签: php xml xml-parsing domdocument


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-07-14
    • 1970-01-01
    • 2018-11-18
    • 2015-06-23
    • 2016-10-23
    • 2019-08-16
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多