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).
The Xml.dom and Xml.sax packages define Python-bound DOM and sax interfaces.
The sub-modules of the XML package include:
- Xml.etree.ElementTree:ElementTree API, lightweight XML processor
- Xml.dom:DOM API
- Xml.dom.minidom: the smallest DOM implementation
- Xml.dom.pulldom: Supporting the construction of some dom trees
- Xml.sax:SAX2 API
- Xml.parsers.expat:Expat Resolver Bindings
xml.dom.minidom
You first need to parse the XML into the DOM, which is done through the parse method.
Parse (Filename_or_file, Parser=none, Bufsize=none)
Returns a Document object
Filename_or_file: File name or File object
Parse: Given must be a SAX2 parsing object
If your XML is written in a string, you can use the ParseString method
ParseString (String, Parser=none)
Python Read and write XML