簡體   English   中英

PHP DOMElement appendChild get DOMException錯誤的文檔錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM