I need to convert an XML ElementTree to a String after altering it. It's the toString part that isn't working.
import xml.etree.ElementTree as ET
tree = ET.parse('my_file.xml')
root = tree.getroot()
for e in root.iter('tag_name'):
e.text = "something else" # This works
# Now I want the the complete XML as a String with the alteration
I've tried various versions of the below line, with ET or ElementTree as various names, and importing toString, etc. etc,
s = tree.tostring(ET, encoding='utf8', method='xml')
I have seen Convert Python ElementTree to string and some others, but I'm not sure how to apply it to my example.
In most scenarios, using str() would be the "cannonical" way to convert an object to a string. Unfortunately, using this with Element returns the object's location in memory as a hexstring, rather than a string representation of the object's data. In Python 2 ElementTree. tostring() also generates a bytestring.
There are two ways to parse the file using 'ElementTree' module. The first is by using the parse() function and the second is fromstring() function. The parse () function parses XML document which is supplied as a file whereas, fromstring parses XML when supplied as a string i.e within triple quotes.
Use lxml. etree.parse(source) to parse the XML file source and return an ElementTree object. Call lxml. etree. tostring(element_or_tree, encoding="unicode" pretty_print=True) to pretty print the contents of the XML file, with element_or_tree as the result of the previous step.
This should work:-
xmlstr = ET.tostring(root, encoding='utf8', method='xml')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With