我有一个xml文件
<root>
<emps>
<employee title="abc">ABC</employee>
<employee title="gef">GEF</employee>
<!-- <employee title="abc">
ABC
</employee>
-->
</emps>
</root>
我想从此文件中删除一些员工详细信息。其他文件delemp.txt abc gh
中提到要删除的员工详细信息import xml.etree.ElementTree as ET
class CommentedTreeBuilder(ET.XMLTreeBuilder):
def __init__(self, *args, **kwargs):
super(CommentedTreeBuilder, self).__init__(*args, **kwargs)
self._parser.CommentHandler = self.comment
def comment(self, data):
self._target.start(ET.Comment, {})
self._target.data(data)
self._target.end(ET.Comment)
parser=CommentedTreeBuilder()
tree = ET.parse('emps.xml', parser)
#tree = ET.parse('emps.xml')
root = tree.getroot()
for e in root.iter('employee'):
print(e.attrib)
val = 'abc'
#mv1 = root.find("./employee[@title='abc']")
#root.remove(mv1)
#th='//employee[title()="'+val'"]'
#xpath='//employee[title()="'+val+'"]'
#mv2 = root.find(xpath)
#print mv2
#root.remove(mv2)
mmm = root.find("//employee[@title='{}']".format(val))
print mmm
root.remove(mmm)
#"//*[@text='{}']".format(email)
tree.write("emps.xml")
tree = ET.parse('emps.xml')
root = tree.getroot()
for movie in root.iter('employee'):
print(e.attrib)
我正在尝试删除xml节点。如果我在xpath中将静态值设为name ='abc'可以正常工作,但是如果我尝试提供动态值则无法正常工作。请帮助我