如何在python中同时删除多个xml元素?
例子:xml文件所示:
<root dirname="xml">
- <dir dirname="b">
<dir dirname="c" />
</dir>
</dir>
- <file>
<filename>as</filename>
<filetype>txt</filetype>
<filehash>d41d8cd98f00b204e9800998ecf8427e</filehash>
<updateclient>Jackie-PC</updateclient>
<current_version>0</current_version>
<master_version>0</master_version>
</file>
<file>
<filename>asass</filename>
<filetype />
<filehash>d6f199804ab7f9425057e940b16851a6</filehash>
<updateclient>Jackie-PC</updateclient>
<current_version>0</current_version>
<master_version>0</master_version>
</file>>
</root>
目的是想删除这块xml文件的这部分内容
“ <file>
<filename>as</filename>
<filetype>txt</filetype>
<filehash>d41d8cd98f00b204e9800998ecf8427e</filehash>
<updateclient>Jackie-PC</updateclient>
<current_version>0</current_version>
<master_version>0</master_version>
</file>”
我的想法是用xpath找到file这个节点,然后寻找其子节点比较filename的名字是否相等,如果相等的话直接返回其父节点,然后用root删除掉该节点,代码如下
node2=root.xpath("/root/file")
for i in range(len(node2)):
... for c in node2[i]:
... if c.text=='as':
... print i
... root.remove(node2[i])
...
0
Traceback (most recent call last):
File "<interactive input>", line 5, in <module>
File "lxml.etree.pyx", line 744, in lxml.etree._Element.remove (src/lxml/lxml.etree.c:32634)
ValueError: Element is not a child of this node.
请问这是啥个原因呢,为什么node2[i]的父节点不是root了呢。。。求大牛解答给个方法呀
[解决办法]
贴一段工整正确的代码这么难吗?