建立和構建 XML 文件
匯入元素樹模組
import xml.etree.ElementTree as ET
Element() 函式用於建立 XML 元素
p=ET.Element('parent')
SubElement() 函式用於為 give 元素建立子元素
c = ET.SubElement(p, 'child1')
dump() 函式用於轉儲 xml 元素。
ET.dump(p)
# Output will be like this
#<parent><child1 /></parent>
如果要儲存到檔案,請使用 ElementTree() 函式建立 xml 樹並儲存到檔案中使用 write() 方法
tree = ET.ElementTree(p)
tree.write("output.xml")
Comment() 函式用於在 xml 檔案中插入註釋。
comment = ET.Comment('user comment')
p.append(comment) #this comment will be appended to parent element