import xml.etree.ElementTree as ET """ ElementTree.write() 將構建的XML文檔寫入(更新)文件。 Element.set(key, value) 添加和修改屬性 Element.text = '' 直接改變字段內容 Element.remove(Element) 刪除Element節點 Element.append(Element) 為當前的Elment對象添加子對象 ET.SubElement(Element,tag)創建子節點 """ # 增加自動縮進換行 def indent(elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.strip(): elem.tail = i for elem in elem: indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i #------------新增XML---------- #創建根節點 a = ET.Element("student") #創建子節點,並添加屬性 b = ET.SubElement(a,"name") b.attrib = {"NO.":"001"} #添加數據 b.text = "張三" #創建elementtree對象,寫文件 indent(a,0) tree = ET.ElementTree(a) tree.write("writeXml.xml",encoding="utf-8") #----------編輯XML-------- # 讀取待修改文件 updateTree = ET.parse("writeXml.xml") root = updateTree.getroot() # --新增-- # 創建新節點並添加為root的子節點 newnode = ET.Element("name") newnode.attrib = {"NO.":"003"} newnode.text = "張三水" root.append(newnode) #---修改--- #----刪除--- # 寫回原文件 indent(root,0) updateTree.write("writeXml.xml",encoding="utf-8", xml_declaration=True)