2013-07-15 59 views
5

我有下面的XML(字符串1):如何使用的SimpleXMLElement PHP替換XML節點

<?xml version="1.0"?> 
<root> 
    <map> 
     <operationallayers> 
     <layer label="Security" type="feature" visible="false" useproxy="true" usePopUp="all" url="http://stackoverflow.com"/> 
     </operationallayers> 
    </map> 
</root> 

而且我有這樣的一段XML(字符串2):

<operationallayers> 
    <layer label="Teste1" type="feature" visible="false" useproxy="true" usePopUp="all" url="http://stackoverflow.com"/> 
    <layer label="Teste2" type="dynamic" visible="false" useproxy="true" usePopUp="all" url="http://google.com"/> 
</operationallayers> 

我用funcion simplexml_load_string既導入到respectives VAR:

$xml1 = simplexml_load_string($string1); 
$xml2 = simplexml_load_string($string2); 

現在,我想替換字符串1的節點「operationallayers」爲string2的節點'operationallayers',但是如何?

類SimpleXMLElement沒有象DOM那樣的'replaceChild'方法。

回答

6

什麼已經SimpleXML: append one tree to another作了概述,您可以導入這些節點到DOMDocument相似的,因爲你寫:

「之類的SimpleXMLElement不具有像DOM方法‘的replaceChild’。」

所以當你導入DOM,你可以使用這些:

$xml1 = simplexml_load_string($string1); 
$xml2 = simplexml_load_string($string2); 

$domToChange = dom_import_simplexml($xml1->map->operationallayers); 
$domReplace = dom_import_simplexml($xml2); 
$nodeImport = $domToChange->ownerDocument->importNode($domReplace, TRUE); 
$domToChange->parentNode->replaceChild($nodeImport, $domToChange); 

echo $xml1->asXML(); 

它給你下面的輸出(非美化):

<?xml version="1.0"?> 
<root> 
    <map> 
     <operationallayers> 
    <layer label="Teste1" type="feature" visible="false" useproxy="true" usePopUp="all" url="http://stackoverflow.com"/> 
    <layer label="Teste2" type="dynamic" visible="false" useproxy="true" usePopUp="all" url="http://google.com"/> 
</operationallayers> 
    </map> 
</root> 

此外,您可以再取這個並將操作添加到您的SimpleXMLElement,以便輕鬆包裝。這是通過從的SimpleXMLElement延伸:

/** 
* Class MySimpleXMLElement 
*/ 
class MySimpleXMLElement extends SimpleXMLElement 
{ 
    /** 
    * @param SimpleXMLElement $element 
    */ 
    public function replace(SimpleXMLElement $element) { 
     $dom  = dom_import_simplexml($this); 
     $import = $dom->ownerDocument->importNode(
      dom_import_simplexml($element), 
      TRUE 
     ); 
     $dom->parentNode->replaceChild($import, $dom); 
    } 
} 

使用例:

$xml1 = simplexml_load_string($string1, 'MySimpleXMLElement'); 
$xml2 = simplexml_load_string($string2); 

$xml1->map->operationallayers->replace($xml2); 

相關:In SimpleXML, how can I add an existing SimpleXMLElement as a child element?

我上次在Stackoverflow上擴展SimpleXMLElement的時間是answer to the "Read and take value of XML attributes" question

+0

@hakre是否有可能使這個命名空間的工作? – Nightwolf

+0

@hakre我爲$ xml2上的特定用例創建了一個名稱空間包裝器,但如果可能的話,將其內置到類中將會很好。 – Nightwolf