php simplexmlelement 修改,如何用SimpleXMLElement PHP替换XML节点

SimpleXML: append one tree to another中概述的类似,您可以将这些节点导入DOMDocument,因为在您编写时:

“The class SimpleXMLElement dont have a method ‘replaceChild’ like the DOM.”

因此,当您导入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();

这给你以下输出(非美化):

此外,您可以将此操作添加到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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值