可查阅标准图书馆的<代码>xml.etree.ElementTree:
import xml.etree.ElementTree as xee
data=
<node1>
<node2 a1="x1"> ... </node2>
<node2 a1="x2"> ... </node2>
<node2 a1="x1"> ... </node2>
</node1>
doc=xee.fromstring(data)
for tag in doc.findall( node2 ):
if tag.attrib[ a1 ]== x2 :
doc.remove(tag)
print(xee.tostring(doc))
# <node1>
# <node2 a1="x1"> ... </node2>
# <node2 a1="x1"> ... </node2>
# </node1>
http://codespeak.net/lxml,该编码不是在标准图书馆,而是有。 更强大的yn子:
import lxml.etree
data=
<node1>
<node2 a1="x1"> ... </node2>
<node2 a1="x2"> ... </node2>
<node2 a1="x1"> ... </node2>
</node1>
doc = lxml.etree.XML(data)
e=doc.find( node2/[@a1="x2"] )
doc.remove(e)
print(lxml.etree.tostring(doc))
# <node1>
# <node2 a1="x1"> ... </node2>
# <node2 a1="x1"> ... </node2>
# </node1>
<><>Edit>: 如果node2
在xml中被掩埋得更深,那么,你可以通过所有标签对每个母体进行检查,看看node2
。 部分是儿童之一,如果是的话,将予以删除:
仅使用xml.etree。 内容 树木:
doc=xee.fromstring(data)
for parent in doc.getiterator():
for child in parent.findall( node2 ):
if child.attrib[ a1 ]== x2 :
parent.remove(child)
使用灯:
doc = lxml.etree.XML(data)
for parent in doc.iter( * ):
child=parent.find( node2/[@a1="x2"] )
if child is not None:
parent.remove(child)