解析和修改XML
代码
注意root.getchildren().index(root.find(‘nm’)) 在python3.9中getchildren作废了,使用list代替
from xml.etree.ElementTree import parse, Element
doc = parse('data/pred.xml')
root = doc.getroot()
print(root)
root.remove(root.find('sri'))
root.remove(root.find('cr'))
child = list(root).index(root.find('nm'))
print(child)
e = Element('spam')
e.text = 'This is test'
root.insert(2, e)
doc.write('data/newpred.xml', xml_declaration=True)