Salathe的答案都幫助我,但因爲我用的SimpleXMLElement的AddChild方法,我在尋找解決辦法,使插入孩子的第一個孩子更加透明。解決的辦法是採取基於DOM的功能,並把它藏在的SimpleXMLElement的一個子類:
class SimpleXMLElementEx extends SimpleXMLElement
{
public function insertChildFirst($name, $value, $namespace)
{
// Convert ourselves to DOM.
$targetDom = dom_import_simplexml($this);
// Check for children
$hasChildren = $targetDom->hasChildNodes();
// Create the new childnode.
$newNode = $this->addChild($name, $value, $namespace);
// Put in the first position.
if ($hasChildren)
{
$newNodeDom = $targetDom->ownerDocument->importNode(dom_import_simplexml($newNode), true);
$targetDom->insertBefore($newNodeDom, $targetDom->firstChild);
}
// Return the new node.
return $newNode;
}
}
畢竟,SimpleXML的允許指定要使用的元素類:
$xml = simplexml_load_file($inputFile, 'SimpleXMLElementEx');
現在,您可以撥打insertChildFirst在任何元素上插入新的孩子作爲第一個孩子。該方法將新元素作爲SimpleXML元素返回,因此它的使用與addChild類似。當然,創建一個insertChild方法很容易,可以指定一個確切的元素來插入項目,但由於我現在不需要,所以我決定不這樣做。
我不確定你可以。從文檔看來,SimpleXML似乎是用於**真正**簡單的操作。 – MvanGeest 2010-07-29 09:36:57
我不能以某種方式在其他地方存儲Cs,刪除它們,添加B,並從該臨時位置添加Cs?我只是不太熟悉PHP .... – 2010-07-29 09:43:03