PHP XML按名称删除元素和所有子元素

我有一个XML文件结构如下:

<root>
  <featured>
    <title></title>
    <tweet></tweet>
    <img></img>
  </featured>
</root> 

元素是动态添加的,用户需要在某些场合删除元素的选项,

我尝试了一些代码变体,包括

        $featureddel = $xpath->query('//featured');

while ( $featureddel->hasChildNodes()){
$featureddel->removeChild($featureddel->childNodes->item(0));
}

这给了我一个错误

PHP Fatal error: Call to undefined method DOMNodeList::hasChildNodes() 

我也尝试过:

$featureddel= $dom->getElementsByTagName('featured');
$featureddel->parentNode->removeChild($featureddel);

返回:

PHP Fatal error: Call to a member function removeChild() on a non-object

解决方法:

DOMElement :: getElementsByTagName和DOMXPath :: query都返回一个DOMNodeList.您的代码似乎期待单个DOMNode.尝试这个:

$featureddel = $xpath->query('//featured');
// OR:
// $featuredde1 = $dom->getElementsByTagName('featured');

foreach ($featuredde1 as $node) {
    $node->parentNode->removeChild($node);
}

编辑:这个确切的代码按预期工作(PHP 5.3,Debian Squeeze):

<?PHP 
$xml = '<root>
  <featured>
    <title></title>
    <tweet></tweet>
    <img></img>
  </featured>
</root>';    
$dom = new DOMDocument();
$dom->loadXML($xml);
$featuredde1 = $dom->getElementsByTagName('featured');

foreach ($featuredde1 as $node) {
    $node->parentNode->removeChild($node);
}
echo $dom->saveXML();

输出是:

<?xml version="1.0"?>
<root>

</root>

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念