douhuireng4407
2008-11-04 16:24
浏览 66

在SimpleXML for PHP中删除具有特定属性的子项

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

<data>
    <seg id="A1"/>
    <seg id="A5"/>
    <seg id="A12"/>
    <seg id="A29"/>
    <seg id="A30"/>
</data>

I need to remove a specific seg element, with an id of "A12", how can I do this? I've tried looping through the seg elements and unsetting the specific one, but this doesn't work, the elements remain.

foreach($doc->seg as $seg)
{
    if($seg['id'] == 'A12')
    {
        unset($seg);
    }
}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

17条回答 默认 最新

  • dongtangu8615 2008-11-04 17:14
    最佳回答

    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='<data>
        <seg id="A1"/>
        <seg id="A5"/>
        <seg id="A12"/>
        <seg id="A29"/>
        <seg id="A30"/>
    </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

    <?xml version="1.0"?>
    <data><seg id="A1"/><seg id="A5"/><seg id="A29"/><seg id="A30"/></data>
    

    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
    
    评论
    解决 无用
    打赏 举报
查看更多回答(16条)

相关推荐 更多相似问题