小编典典
以下是在其他一些SimpleXMLElement之后插入新的SimpleXMLElement的函数。由于使用SimpleXML不可能直接做到这一点,因此它在幕后使用了一些DOM类/方法来完成工作。
function simplexml_insert_after(SimpleXMLElement $insert, SimpleXMLElement $target)
{
$target_dom = dom_import_simplexml($target);
$insert_dom = $target_dom->ownerDocument->importNode(dom_import_simplexml($insert), true);
if ($target_dom->nextSibling) {
return $target_dom->parentNode->insertBefore($insert_dom, $target_dom->nextSibling);
} else {
return $target_dom->parentNode->appendChild($insert_dom);
}
}
以及如何使用它的示例(特定于您的问题):
$sxe = new SimpleXMLElement('');
// New element to be inserted
$insert = new SimpleXMLElement("");
// Get the last nodeA element
$target = current($sxe->xpath('//nodeA[last()]'));
// Insert the new element after the last nodeA
simplexml_insert_after($insert, $target);
// Peek at the new XML
echo $sxe->asXML();
如果您想/需要解释它是 如何 工作的(代码相当简单,但可能包含外国概念),只需询问即可。
2020-05-29