[英]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作为子元素添加到另一个元素中?
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.