如何用SimpleXMLElement PHP替换XML节点
我有以下XML(string1): 现在,我想将string1的节点'operationallayers'替换为string2的节点'operationallayers',但是如何替换呢如何用SimpleXMLElement PHP替换XML节点,php,xml,simplexml,Php,Xml,Simplexml,我有以下XML(string1): 现在,我想将string1的节点'operationallayers'替换为string2的节点'operationallayers',但是如何替换呢 SimpleXMLElement类没有像DOM那样的“replaceChild”方法。类似于中概述的方法,您可以将这些节点导入到DOMDocument中,因为在编写时: “SimpleXMLElement类没有像DOM那样的“replaceChild”方法。” 因此,当您导入DOM时,可以使用以下各项: $xm
SimpleXMLElement类没有像DOM那样的“replaceChild”方法。类似于中概述的方法,您可以将这些节点导入到
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();
这将为您提供以下输出(非美化):
用法示例:
$xml1 = simplexml_load_string($string1, 'MySimpleXMLElement');
$xml2 = simplexml_load_string($string2);
$xml1->map->operationallayers->replace($xml2);
相关:
上一次我在Stackoverflow上扩展SimpleXMLElement时遇到了一个问题。@hakre有可能在名称空间上实现这一点吗?@hakre我在$xml2上为我的特定用例创建了一个名称空间包装器,但如果可能的话,最好将其内置到类中。
$xml1 = simplexml_load_string($string1);
$xml2 = simplexml_load_string($string2);
$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>
/**
* 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);