Converting a Python XML ElementTree to a String

user984003 picture user984003 · Nov 19, 2015 · Viewed 28.5k times · Source

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.

Answer

Stephen Briney picture Stephen Briney · Nov 19, 2015

This should work:-

xmlstr = ET.tostring(root, encoding='utf8', method='xml')