Python parsing of XML
The common XML programming interface has DOM and sax, and the two interfaces handle XML files in different ways, of course, using different scenarios.
Python has three ways to parse Xml,sax,dom, and ElementTree:
1.SAX (Simple API for XML)
The Python standard library contains the SAX parser, which uses the event-driven model to process XML files by triggering events and invoking user-defined callback functions during parsing of XML.
2.DOM (Document Object Model)
Parses XML data into a tree in memory, manipulating the XML by manipulating the tree.
3.ElementTree (element Tree)
ElementTree is like a lightweight dom, with a convenient and friendly API. Good code availability, fast speed, low memory consumption.
Note: because the DOM needs to map XML data to a tree in memory, one is slower, the other is less memory, and Sax streams the XML file faster and consumes less memory, but requires the user to implement the callback function (handler).
Above from: http://www.runoob.com/python/python-xml.html
Where ElementTree used much, I used it to generate XML tree success, but with the generation of XML files because the tree structure contains Chinese nodes (the following code in the "Chinese" word), resulting in the creation of the XM file of the Chinese part is garbled, and the method of the Internet can not be solved.
ImportElementTree. ElementTree as Etcountry=et. Element ("Country") Country.set ("name",'China') Province1=et. subelement (Country,'Province') Tree=ET. ElementTree (country); Tree.write (R'C:\Users\hhx\Desktop\country.xml', encoding='GBK')
ElementTree's basic official tutorials :
ImportElementTree. ElementTree as ET#Build a tree structureroot = ET. Element ("HTML") Head= ET. subelement (Root,"Head") Title= ET. Subelement (Head,"title") Title.text="Page Title"Body= ET. subelement (Root,"Body") Body.set ("bgcolor","#ffffff") Body.text="Hello, world!."#Wrap it in an ElementTree instance, and save as XMLTree =ET. ElementTree (Root) tree.write ("page.xhtml")
Later, the idea was changed, using the Xml.dom.minidom module to create the XML tree structure and export the XML file, and then use the ElementTree to read, parse, and find.
Python Read and write XML