I’m currently trying to build a function that exports some data as XML. The code does output with no errors, but all of the XML is on a single line. Any ideas?
from lxml import etree def exportAsXML(filename): fields = [ ('Realm', 'Midgard'), ('ActiveState', 'Dropped'), ('Name', 'Test Item'), ('Type', 'Bracer'), ('Level', '50'), ('Quality', '100'), ('Bonus', '35'), ('AFDPS', ''), ('Speed', ''), ('Origin', 'Quest'), ('DamageType', ''), ('LeftHand', ''), ('Requirement', 'Level 50'), ('Notes', '') ] root = etree.Element('Item') for key, value in fields: if value != '': etree.SubElement(root, key).text = value document = open(filename, 'wb') document.write(etree.tostring(root, encoding='UTF-8', pretty_print = True)) document.close() exportAsXML('output.xml')
What I’ve tried:
I have appended .decode('UTF-8')
to the end of the write statement which DOES output correctly:
<Item> <Realm>Midgard</Realm> ... </Item>
However, it was suggested that I shouldn’t have to do this.
Looking over the LXML documentation I read the tidbit about pretty_print
not working because the original document contained formatting that needed to be stripped first, but I’m not parsing this from another XML document, so I don’t see how that applies.