123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- 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
-
- a = ET.Element("student")
- b = ET.SubElement(a,"name")
- b.attrib = {"NO.":"001"}
- b.text = "張三"
- indent(a,0)
- tree = ET.ElementTree(a)
- tree.write("writeXml.xml",encoding="utf-8")
- updateTree = ET.parse("writeXml.xml")
- root = updateTree.getroot()
- 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)
|