How would you get the source of an ElementTree as a string in Python?
2 Answers
import xml.etree.ElementTree as ET
tree = ET.parse(source)
root = tree.getroot()
ET.tostring(root)
Note that there may be formatting differences between the content of source and ET.tostring(doc).
4 Comments
James
'ElementTree' object has no attribute 'tostring' happens when I tried this
Martijn Pieters
@James: then you are calling it on the wrong object. It's the module that has that method.
unutbu
@James: You are right that
ET.tostring(tree) does not work if tree is an ElementTree (my mistake). Instead, get the root of the tree with root = tree.getroot(), and then call ET.tostring(root).James
@MartijnPieters Yes! Thank you for pointing that out. I will accept as soon as I can