Incremental XML generation questions
Hi! I'm interested in incremental XML generation. I have two questions: 1. Is it somehow possible to first create an element, then open it with context manager? The reasoning for this is that I have pretty complicated elements and I'm using a helper library to create them, so it would be useful to just get the element from the helper library and start writing to it. I'm thinking something like this, but this does not work: f = BytesIO() with etree.xmlfile(f) as xf: element = helper_library.create_root_element(...) with element: xf.write('text') 2. Is it possible to clean up unused namespaces from an element when generating XML incrementally? The problem is that the lxml.etree.cleanup_namespaces function wants the element as an argument, but I have not come up with a way to access the element with incremental XML generation: f = BytesIO() with etree.xmlfile(f) as xf: # How to access the element created below? # with xf.element('abc') as element does not seem to work with xf.element('abc'): xf.write(...) # Now I have nothing to give to this function: lxml.etree.cleanup_namespaces(tree_or_element=":(")
I came up with a pretty good workaround for the first question: f = BytesIO() with etree.xmlfile(f) as xf: element = helper_library.create_root_element(...) with xf.element(tag=element.tag, attrib=element.attrib, nsmap=element.nsmap): xf.write('text') But answers to the second question would still be appreciated :)
participants (1)
-
matias.wargelin@gmail.com