嗨,我想知道如何在新创建的Appendid子节点中附加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);
这是新创建的Child,
$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();
输出:
<?xml version="1.0"?>
<new>sample<foo/><tag/>text</new>