perl 如何删除xml节点?
my $parser=new XML::DOM::Parser;
my $doc=$parser->parsefile("d://news_temp.xml");
my $nodes=$doc->getElementsByTagName("allProperty");
$doc->removeChild($nodes); 这句怎么写??
#########################################################################
news_temp.xml
<root>
<allProperty> # 要删除这个节点
<news_title></news_title>
</allProperty>
</root>
[解决办法]
http://search.cpan.org/~tjmather/XML-DOM-1.44/lib/XML/DOM/Node.pod
removeChild (oldChild)
Removes the child node indicated by oldChild from the list of children, and returns it.
Return Value: The node removed.
DOMExceptions:
NO_MODIFICATION_ALLOWED_ERR
Raised if this node is readonly.
NOT_FOUND_ERR
Raised if oldChild is not a child of this node.
[解决办法]
最关键的一个地方你写错了
my $nodes=$doc->getElementsByTagName("allProperty"); 这里返回的应该是数组。所以你不应该用$nodes.应该用@nodes
$doc->removeChild($nodes); 这里呢,你必须针对每个node单独处理。可以针对@nodes for一下
[解决办法]
my $parser=new XML::DOM::Parser; my $doc=$parser->parsefile("d://news_temp.xml"); my $nodes=$doc->getElementsByTagName("allProperty"); my $parent=$nodes->[0]->getParentNode();$parent->removeChild($nodes->[0]);
[解决办法]
use strict;use warnings;use XML::DOM;my $parser=new XML::DOM::Parser; my $doc=$parser->parse(<<XML);<root> <allProperty> <news_title>yes</news_title> </allProperty></root> XMLmy $nodes = $doc->getElementsByTagName("allProperty");my $node = $nodes->item(0);$node->getParentNode->removeChild($node); # delete allPropertyprint $doc->toString();