SAX (simple API for XML) It functions as a stream parser, with an event-driven API.
DOM (Document Object Model) It reads the XML into memory and converts it to objects that can be accessed with Python.
ElementTree
ElementTree is much easier to use, because it represents an XML tree (basically) as a structure of lists, and attributes are represented as dictionaries.
ElementTree needs much less memory for XML trees than DOM (and thus is faster), and the parsing overhead via (凭借) iterparse is comparable to SAX. Additionally, iterparse returns partial structures, and you can keep memory usage constant during parsing by discarding the structures as soon as you process them.
ElementTree, as in Python 2.5, has only a small feature set compared to full-blown XML libraries, but it’s enough for many applications. If you need a validating parser or complete XPath support, lxml is the way to go. For a long time, it used to be quite unstable, but I haven’t had any problems with it since 2.1.
ElementTree deviates (脱离) from DOM, where nodes have access to their parent and siblings. Handling actual documents rather than data stores is also a bit cumbersome (笨重的,难处理的), because text nodes aren’t treated as actual nodes. In the XML snippet
# 元素开始调用 defstartElement(self, tag, attributes): self.CurrentData = tag if tag == "movie": print("*****Movie*****") title = attributes["title"] print("Title:", title)
import xml.etree.ElementTree as ET tree = ET.parse('movies.xml') root = tree.getroot() tag = root.tag attrib = root.attrib print("root:{0},shelf:{1}".format(tag, attrib.get('shelf')))
for child in root: print(child.tag, child.attrib) title = child.get('title') format = child.find('format').text rating = child.find('rating').text stars = child.find('stars').text description = child.find('description').text print('***movie***') print("title:{}".format(title)) print("type:{}".format(format))