I have a Python function that writes xml string to a file. The code is as follows:
My file_contents is a string as follows:
<A>Some Text</A>
<B>Some other Text</B>
I would like to enclose this string inside and prepend the xml header : to the file. I can't seem to figure this out.
from lxml import etree
def create_or_overwrite_file(file_name, file_contents):
try:
print('file contents to be written: %s' % file_contents)
'''
#root = etree.fromstring(file_contents) #this line definitely fails because file_contents is NOT a valid XML
#print('root: %s' % str(root))
#newroot = etree.Element('RootElement')
#newroot.insert(0, root)
#print('newroot: %s' % newroot)
#new_file_contents = etree.tostring(newroot)
#print('NewFileContents: %s' % str(new_file_contents))
'''
root = etree.fromstring(file_contents).getroot()
et = etree.ElementTree(root)
with open(str(file_name), "wb") as f:
et.write(f, encoding="utf-8", xml_declaration=True, pretty_print=True)
print('wrote file_contents to %s' % str(file_name))
except Exception as f:
print(str(f))
I can't seem to get this code working. Any help is appreciated.