且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除具有特定属性的小孩,在SimpleXML for PHP中

更新时间:2023-02-23 08:31:59

SimpleXML 提供一种删除节点的方法,其修改功能有所限制。另一个解决方案是诉诸使用 DOM 扩展程序。 dom_import_simplexml()将帮助您转换您的 SimpleXMLElement 到一个 DOMElement

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.

只是一些示例代码用PHP 5.2.5测试):

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

输出

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

顺便说一下:使用XPath时,选择特定的节点要简单得多( SimpleXMLElement-> xpath ):

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