This article is an example of using ElementTree to generate an XML file for a class library
# *-* coding=utf-8from xml.etree.ElementTree import elementtreefrom xml.etree.ElementTree import Elementfrom Xml.etree.ElementTree Import subelementfrom xml.etree.ElementTree import dumpfrom xml.etree.ElementTree Import Commentfrom xml.etree.ElementTree import tostringimport osfilename= "Book.xml" Def Createxml (): Book =elementtree () Purorder =element ("PurchaseOrder") book._setroot (purorder) List = Element ("account", {' Idsn ': ' 2390094 '}) Purorder.append (list) item = Element ("Item1", {"SKU": "ABCD", "Qty": "4"}) subelement (item, "Name"). text= "Potato smasher "Subelement (item," Description "). text=" Smash potatoes like Never before "purorder.append (item) item = Element (" item2 ", { "SKU": "Gfhi", "Qty": "+"}) subelement (item, "Name"). text= "Beijing" subelement (item, "Description"). text= "My Country" Purorder.append (item) indent (Purorder) return bookdef indent (elem,level=0): i = "\ n" +level* "" Print Elem;if len (elem): if Not elem.text or not Elem.text.strip (): Elem.text = i + "" for E in Elem:print eindent (e,level+1) if not E. Tail or not E.tail.strip (): E.tail =iif level and (not elem.tail or not Elem.tail.strip ()): Elem.tail =ireturn elemif __nam e__ = = ' __main__ ': Book =createxml () book.write (filename, "Utf-8") #book. Write ("Book2.xml", "Utf-8", True) #true are with XML declaration
Python to create an XML file