![](https://secure.gravatar.com/avatar/8b97b5aad24c30e4a1357b38cc39aeaa.jpg?s=120&d=mm&r=g)
Stefan Behnel, 10.11.2012 17:34:
Stefan Behnel, 01.11.2012 22:56:
Actually, I'd love to see someone implement a magic API like this:
# open an "XMLFile" object that knows about XML serialisation with xmlfile("somefile.xml", encoding='utf-8') as xf: # generate an element (the root element) with xf.Element('root-tag') as root_element: # generate content, e.g. through iterparse for element in generate_some_elements(): # serialise generated elements into the XML file xf.write(element)
That looks like it should be totally trivial to do, but would make the above use case way simpler and safer.
Thanks everyone for the comments. However, I really meant it the way I showed above. The use case is to freely (and efficiently) mix in-memory trees with incrementally generated content, and to safely write everything out into a file as it is being generated. In fact, the most important use case is to write out an XML declaration with a root element and then only write out in-memory trees one by one into that root element, e.g. coming from iterparse with some intermediate processing. Most of the code for that is already in serialiser.pxi anyway.
One bug in the above code example:
with xf.Element('root-tag') as root_element:
This should simply read with xf.Element('root-tag'): because it doesn't make sense (and, in fact, would be problematic) to provide access to an element that was already serialised. I've started to drop the above into an implementation. Looks good so far. Stefan