0%
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| from xml.etree.ElementTree import ElementTree, Element
def read_xml(in_path): '''读取并解析xml文件''' tree = ElementTree() tree.parse(in_path) return tree
def write_xml(tree, out_path): '''保存xml文件''' tree.write(out_path, encoding="utf-8", xml_declaration=False)
if __name__ == "__main__": tree = read_xml("femalasadzzl0.xml")
root = tree.getroot() for child in root.getchildren(): if child.tag == 'object': child[2].text = '0' child[3].text = '0'
write_xml(tree, 'femalasadzzl0.xml')
|
进一步修改,实现当前目录下xml批量更新
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| from xml.etree.ElementTree import ElementTree, Element import os
def read_xml(in_path): tree = ElementTree() tree.parse(in_path) return tree
def write_xml(tree, out_path): tree.write(out_path, encoding="utf-8", xml_declaration=False)
def update_xml(path): tree = read_xml(path) root = tree.getroot()
for child in root.getchildren(): if child.tag == 'object': child[2].text = '0' child[3].text = '0'
write_xml(tree, path)
if __name__ == "__main__": fpath = os.path.dirname(os.path.abspath(__file__)) os.chdir(fpath) path = os.getcwd() filelist = os.listdir(path) for fn in filelist: if fn.endswith('xml'): print(fn) update_xml(fn)
|