Php DOMDocument如何附加到createDocumentFragment中新附加的子元素?

Php DOMDocument如何附加到createDocumentFragment中新附加的子元素?,php,xml,domdocument,Php,Xml,Domdocument,嗨,我想知道如何在新创建的附加子节点中附加XML标记 这是我的 $newNode = $xml->createDocumentFragment(); $reCreateOldNode = $xml->createElement("myNewChild"); $newNode->appendChild($reCreateOldNode); // This is Newly Appended Child while ($node->f

嗨,我想知道如何在新创建的附加子节点中附加XML标记

这是我的

$newNode = $xml->createDocumentFragment();
$reCreateOldNode = $xml->createElement("myNewChild");
$newNode->appendChild($reCreateOldNode);         // This is Newly Appended Child
   while ($node->firstChild) {
     $match->nodeValue = "";
     $newNode->appendChild($node->firstChild);
     $newNode->appendXML($actionOutput);        // I want to Append the XML to $newNode->myNewChild
   }
$node->parentNode->replaceChild($newNode, $node);
这是新创建的子对象

$newNode->appendChild($reCreateOldNode);  

我想将我创建的XML直接附加到
$newNode->myNewChild
而不是
$newNode
上。

文档片段的实际用途是允许您将节点列表(元素、文本节点、注释…)视为单个节点,并将它们用作DOM方法的参数。您只需要附加一个节点(及其子节点)——无需将此节点附加到片段

在PHP中,文档片段可以解析XML片段字符串。因此,您可以使用它将字符串解析为XML片段,然后将其附加到DOM节点。此片段将附加到新节点

$document = new DOMDocument();
$document->loadXML('<old>sample<foo/></old>');
$node = $document->documentElement;

// create the new element and store it in a variable
$newNode = $document->createElement('new');
// move over all the children from "old" $node
while ($childNode = $node->firstChild) {
    $newNode->appendChild($childNode);
}

// create the fragment for the XML snippet
$fragment = $document->createDocumentFragment();
$fragment->appendXML('<tag/>text');

// append the nodes from the snippet to the new element
$newNode->appendChild($fragment);

$node->parentNode->replaceChild($newNode, $node);

echo $document->saveXML();
$document=新的DOMDocument();
$document->loadXML('sample');
$node=$document->documentElement;
//创建新元素并将其存储在变量中
$newNode=$document->createElement('new');
//从“old”$node移到所有子节点
而($childNode=$node->firstChild){
$newNode->appendChild($childNode);
}
//为XML片段创建片段
$fragment=$document->createDocumentFragment();
$fragment->appendXML('text');
//将代码段中的节点追加到新元素
$newNode->appendChild($fragment);
$node->parentNode->replaceChild($newNode,$node);
echo$document->saveXML();
输出:

<?xml version="1.0"?>
<new>sample<foo/><tag/>text</new>

样本文本

你的意思是像
$appendNode=$newNode->appendChild($reCreateOldNode)
,然后将新节点添加到
$appendNode
(再次使用
appendChild()
)中。我使用它来简化我的xml工作流程,即我一直使用appendXML而不是appendChild@NigelRen在附加子$reCreateOldNode之后,我想附加一个appendXML而不是appendChild,因为我只准备了XML标记,然而,当我尝试将XML附加到$newnodec时,我得到了未定义的函数appendXML。当您已经操作DOM本身时,自己创建XML似乎是一个奇怪的想法。(它也可能容易出错)。可能有帮助-它基本上导入XML,然后处理追加。