Remove a child with a specific attribute, in SimpleXML for PHP

后端 未结 17 2409
星月不相逢
星月不相逢 2020-11-22 02:50

I have several identical elements with different attributes that I\'m accessing with SimpleXML:


    
    

        
17条回答
  •  被撕碎了的回忆
    2020-11-22 03:17

    While SimpleXML provides a way to remove XML nodes, its modification capabilities are somewhat limited. One other solution is to resort to using the DOM extension. dom_import_simplexml() will help you with converting your SimpleXMLElement into a DOMElement.

    Just some example code (tested with PHP 5.2.5):

    $data='
        
        
        
        
        
    ';
    $doc=new SimpleXMLElement($data);
    foreach($doc->seg as $seg)
    {
        if($seg['id'] == 'A12') {
            $dom=dom_import_simplexml($seg);
            $dom->parentNode->removeChild($dom);
        }
    }
    echo $doc->asXml();
    

    outputs

    
    
    

    By the way: selecting specific nodes is much more simple when you use XPath (SimpleXMLElement->xpath):

    $segs=$doc->xpath('//seq[@id="A12"]');
    if (count($segs)>=1) {
        $seg=$segs[0];
    }
    // same deletion procedure as above
    

提交回复
热议问题