追加DOMDocument根元素到另一个DOMDocument


Append DOMDocument root element to another DOMDocument

我有2个"DOMDocument"对象- $original和$additional。我想要的是从$additional DOMDocument中获取所有子节点,并将其附加到$original document的末尾。

我的计划是取$additional文档的根元素。我尝试使用:

$root = $additional->documentElement;
$original->appendChild($root)

但是我收到错误,appendChild期望DOMNode对象作为参数。我尝试通过:

访问文档的每个子节点
$additional->childNodes->item(0);

但是它返回DOMElement的对象。你能建议如何获得DOMNode类的对象吗?提供这个导入操作最方便的方法是什么?

$original XML看起来像:

<?xml version="1.0" encoding="utf-8"?>
<Product>
     <RecordReference>345345</RecordReference>
     <NotificationType>03</NotificationType>
     <NumberOfPages>100</NumberOfPages 
</Product>

$additional XML看起来像:

<?xml version="1.0" encoding="utf-8"?>
<MainSubject>
    <SubjectScheme>10</SubjectScheme>
</MainSubject>

我想要的:

<?xml version="1.0" encoding="utf-8"?>
<Product>
     <RecordReference>345345</RecordReference>
     <NotificationType>03</NotificationType>
     <NumberOfPages>100</NumberOfPages>
     <MainSubject>
         <SubjectScheme>10</SubjectScheme>
     </MainSubject> 
</Product>

DOMElement是一个DOMNode, DOMNode是它的超类。下面是元素、文本和其他节点的几个子类。只需迭代、导入和追加它们即可。

$targetDom = new DOMDocument();
$targetDom->loadXML('<root/>');
$sourceDom = new DOMDocument();
$sourceDom->loadXml('<items><child/>TEXT</items>');
foreach ($sourceDom->documentElement->childNodes as $child) {
  $targetDom->documentElement->appendChild(
    $targetDom->importNode($child, TRUE)
  );
}

这也适用于document元素。

$targetDom = new DOMDocument();
$targetDom->loadXML('<root/>');
$sourceDom = new DOMDocument();
$sourceDom->loadXml('<items><child/>TEXT</items>');
$targetDom->documentElement->appendChild(
  $targetDom->importNode($sourceDom->documentElement, TRUE)
);
echo $targetDom->saveXml();

DOMDocument::importNode()在文档的上下文中创建所提供节点的副本。只有属于文档的节点才能添加到文档中。