generate xml with sax2 in python
I have a data model or an object from a class, and I need to initialize it by reading from an 开发者_JS百科xml file, or create this object from scratch and output it to an xml file. Previously, I simply use string operations from python to read xml (file.read + string.find) and write xml (file.write), without error checking.
Now I am thinking to use Sax2 to do this. I know how to do it for the read, but not very clear about write. It looks like the sax2 is used for the case when there is an original xml and you want to output after certain modifications. In my case I want to output my data model to xml, with no original xml at all. I wonder if sax2 is good or suitable for this or I should keep using my old way. What is the better way to input/output a class object from/to XML with python? The class is very simple (just a list collection of a list information, i.e., root -> children -> grandchildren) and small size.
Thanks for any suggestions.
Try the pythonic XML processing way: ElementTree
.
Generating XML output is easy with`xml.etree.ElementTree.ElementTree.write().
write(file, encoding="us-ascii", xml_declaration=None, method="xml")
Writes the element tree to a file, as XML. file is a file name, or a file object opened for writing. encoding 1 is the output encoding (default is US-ASCII). xml_declaration controls if an XML declaration should be added to the file. Use False for never, True for always, None for only if not US-ASCII or UTF-8 (default is None). method is either "xml", "html" or "text" (default is "xml"). Returns an encoded string.
Example loading ElementTree
object from text file:
>>> from xml.etree.ElementTree import ElementTree
>>> tree = ElementTree()
>>> tree.parse("index.xhtml")
精彩评论