删除具有特定属性的小孩,在SimpleXML for PHP中 [英] Remove a child with a specific attribute, in SimpleXML for PHP
问题描述
我有几个与SimpleXML访问不同属性的相同元素:
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>
我需要删除特定的 seg 元素,ID为 A12,我该怎么办?我尝试循环使用 seg 元素和取消设置特定的元素,但这不起作用,元素依然存在。
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);
}
}
推荐答案
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
这篇关于删除具有特定属性的小孩,在SimpleXML for PHP中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!