'How to dump, load and read struct from XML in Python

I have a data

data = { 
   'words': """ 
        Lorem ipsum dolor sit amet, consectetur adipiscing 
        elit. Mauris adipiscing adipiscing placerat. 
        Vestibulum augue augue, 
        pellentesque quis sollicitudin id, adipiscing. 
        """, 
   'list': list(range(100)), 
   'dict': dict((str(i),'a') for i in iter(range(100))), 
   'int': 100, 
   'float': 100.123456,
   'boolean' : True
}

And I try to dump and read it

import xml.etree.ElementTree as ET
from dicttoxml import dicttoxml
import xmltodict

with open('file.xml', 'w') as handle:
    start_time = time()
    xml = dicttoxml(data, handle, attr_type=False)
    dump_time = time() - start_time
    handle.write(xml.decode('utf-8').replace("\n", "\\n"))

file_size = os.stat('file.xml').st_size

# Load data (deserialize)
start_time = time()
tree = ET.parse('file.xml')
root = tree.getroot()
load_time = time() - start_time

print(f'XML:\n \tdump time: {dump_time}\n \tload time: {load_time}\n \tfile size {file_size}')

But i get an error :

 tree = ET.parse('file.xml')
  File "/usr/local/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/xml/etree/ElementTree.py", line 1229, in parse
    tree.parse(source, parser)
  File "/usr/local/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/xml/etree/ElementTree.py", line 580, in parse
    self._root = parser._parse_whole(source)
xml.etree.ElementTree.ParseError: junk after document element: line 1, column 233


Solution 1:[1]

xml = dicttoxml(data, custom_root='test', attr_type=False)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ivan Dobryaev