微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何用SimpleXMLElement PHP替换XML节点

我有以下XML(string1):

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

我有这段XML(string2):

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

我使用函数simplexml_load_string将两者都导入到各自的var:

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

现在,我想为string2的节点’operationslayers’替换string1的节点’operationallayers’,但是如何?

SimpleXMLElement类没有像DOM那样的方法’replaceChild’.

解决方法:

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();

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

<?xml version="1.0"?>
<root>
   <map>
      <operationallayers>
    <layer label="Teste1" type="feature" visible="false" useproxy="true" usePopUp="all" url="https://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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐