Open whuizhe opened 6 years ago
Hi, If I am getting you right then I think you want to convert XML tree structure into a string. Please look at the following code for this conversion
from xml.etree import ElementTree
# in xyz.xml = "<root><x x="1"/><y><z/></y></root>"
root = ElementTree.parse('xyz.xml')
def tostring(element, encoding=None, method=None):
stream = io.StringIO() if encoding == 'unicode' else io.BytesIO()
for elem in element.getiterator():
ElementTree.ElementTree(elem).write(stream, encoding, method=method)
return stream.getvalue()
tostring(root, encoding='utf-8') # outcome = "<root><x x="1"/><y><z/></y></root>"
test = tostring(test01, encoding='utf-8')
encoding='utf-8' is invalid
def tostring(element, encoding=None, method=None, *, short_empty_elements=True): stream = io.StringIO() if encoding == 'unicode' else io.BytesIO() ElementTree(element).write(stream, encoding, method=method, short_empty_elements=short_empty_elements) return stream.getvalue()