"""illustrates a quick and dirty way to persist an XML document expressed usingElementTree and pickle.This is a trivial example using PickleType to marshal/unmarshal the ElementTreedocument into a binary column. Compare to explicit.py which stores theindividual components of the ElementTree structure in distinct rows using twoadditional mapped entities. Note that the usage of both styles of persistenceare identical, as is the structure of the main Document class."""importosfromxml.etreeimportElementTreefromsqlalchemyimportColumnfromsqlalchemyimportcreate_enginefromsqlalchemyimportIntegerfromsqlalchemyimportPickleTypefromsqlalchemyimportStringfromsqlalchemyimportTablefromsqlalchemy.ormimportregistryfromsqlalchemy.ormimportSessione=create_engine("sqlite://")mapper_registry=registry()# setup a comparator for the PickleType since it's a mutable# element.defare_elements_equal(x,y):returnx==y# stores a top level record of an XML document.# the "element" column will store the ElementTree document as a BLOB.documents=Table("documents",mapper_registry.metadata,Column("document_id",Integer,primary_key=True),Column("filename",String(30),unique=True),Column("element",PickleType(comparator=are_elements_equal)),)mapper_registry.metadata.create_all(e)# our document class. contains a string name,# and the ElementTree root element.classDocument(object):def__init__(self,name,element):self.filename=nameself.element=element# setup mapper.mapper_registry.map_imperatively(Document,documents)# time to test !# get ElementTree documentfilename=os.path.join(os.path.dirname(__file__),"test.xml")doc=ElementTree.parse(filename)# save to DBsession=Session(e)session.add(Document("test.xml",doc))session.commit()# restoredocument=session.query(Document).filter_by(filename="test.xml").first()# printElementTree.dump(document.element)