XML Parsing with Decode in Python

so you can try this, but this returns an Element Instance

import ast
import xml.etree.ElementTree as etree


tree = None 

with open("property.xml", "r") as xml_file:
     f = xml_file.read()
     
     # convert string representation of bytes back to bytes
     raw_xml_bytes= ast.literal_eval(f)
     
     # read XML from raw bytes
     tree = etree.fromstring(raw_xml_bytes)

Another way is to read the file and convert it fully to a string file and then reread it again, this returns an ElementTree instance. You can achieve this using the following:

tree = None

with open("property.xml", "r") as xml_file:
    f = xml_file.read()
     
    # convert string representation of bytes back to bytes
    raw_xml_bytes= ast.literal_eval(f)

# save the converted string version of the XML file
with open('output.xml', 'w') as file_obj:
    file_obj.write(raw_xml_bytes.decode())

# read saved XML file 
with open('output.xml', 'r') as xml_file:
    tree = etree.parse(f)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top