我有一个结构为的 XML 文件:
<root>
<featured>
<title></title>
<tweet></tweet>
<img></img>
</featured>
</root>
Run Code Online (Sandbox Code Playgroud)
元素是动态添加的,用户需要选择在某些情况下删除元素,
我尝试了一些代码变体,包括:
$featureddel = $xpath->query('//featured');
while ( $featureddel->hasChildNodes()){
$featureddel->removeChild($featureddel->childNodes->item(0));
}
Run Code Online (Sandbox Code Playgroud)
这给了我一个错误:
PHP Fatal error: Call to undefined method DOMNodeList::hasChildNodes()
Run Code Online (Sandbox Code Playgroud)
我也试过:
$featureddel= $dom->getElementsByTagName('featured');
$featureddel->parentNode->removeChild($featureddel);
Run Code Online (Sandbox Code Playgroud)
返回:
PHP Fatal error: Call to a member function removeChild() on a non-object
Run Code Online (Sandbox Code Playgroud)
双方DOMElement::getElementsByTagName并DOMXPath::query返回DOMNodeList。您的代码似乎需要一个DOMNode。尝试这个:
$featureddel = $xpath->query('//featured');
// OR:
// $featuredde1 = $dom->getElementsByTagName('featured');
foreach ($featuredde1 as $node) {
$node->parentNode->removeChild($node);
}
Run Code Online (Sandbox Code Playgroud)
编辑:这个确切的代码对我来说按预期工作(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();
Run Code Online (Sandbox Code Playgroud)
输出是:
<?xml version="1.0"?>
<root>
</root>
Run Code Online (Sandbox Code Playgroud)