PHP XML按名称删除元素和所有子项 [英] PHP XML remove element and all children by name
问题描述
我有一个XML文件结构如下:
< root>
< featured>
< title>< / title>
< tweet>< / tweet>
< img>< / img>
< / featured>
< / root>
元素被动态添加,用户需要在某些场合删除元素的选项, p>
我尝试了一些代码,包括:
$ featureddel = $ xpath->查询( '//功能');
while($ featureddel-> hasChildNodes()){
$ featureddel-> removeChild($ featureddel-> childNodes-> item(0));
}
这给我一个错误:
PHP致命错误:调用未定义的方法DOMNodeList :: hasChildNodes()
Ive也试过:
$ featureddel = $ dom-> getElementsByTagName('featured');
$ featureddel-> parentNode-> removeChild($ featureddel);
返回:
PHP致命错误:调用非对象上的成员函数removeChild()
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>
I have an XML file structured as:
<root>
<featured>
<title></title>
<tweet></tweet>
<img></img>
</featured>
</root>
The element is added dynamically , the user needs the option to remove the element on certain occasions,
I have tried a few variations of code including:
$featureddel = $xpath->query('//featured');
while ( $featureddel->hasChildNodes()){
$featureddel->removeChild($featureddel->childNodes->item(0));
}
which gives me a error:
PHP Fatal error: Call to undefined method DOMNodeList::hasChildNodes()
Ive also tried:
$featureddel= $dom->getElementsByTagName('featured');
$featureddel->parentNode->removeChild($featureddel);
which returns:
PHP Fatal error: Call to a member function removeChild() on a non-object
Both DOMElement::getElementsByTagName
and DOMXPath::query
return a DOMNodeList
. Your code seems to be expecting a single DOMNode
instead. Try this:
$featureddel = $xpath->query('//featured');
// OR:
// $featuredde1 = $dom->getElementsByTagName('featured');
foreach ($featuredde1 as $node) {
$node->parentNode->removeChild($node);
}
Edit: This exact code works as expected for me (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();
The output is:
<?xml version="1.0"?>
<root>
</root>
这篇关于PHP XML按名称删除元素和所有子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!