php - 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();
推荐阅读
- c# - 我可以使用 InkManager.RecognizeAsync 来识别数学公式吗?
- python-3.x - 在python3.6中反转字符数组
- python - Python Yahoo-Finance Try-Except with Continue for Problem Tickers in a List
- c# - LINQ where 子句中的 DateTime 属性错误
- jquery - jQuery 仅在 Rails 站点上本地工作
- visual-studio - 我只能在 HoloLens 上部署 1 个 Unity 应用
- java - java中添加二维数组的方法向量的问题
- php - 我想根据员工姓名打印负责人的姓名
- python - 去序列化二叉搜索树
- python - 有没有办法继承指向类自己的私有变量的方法?