10

How would you get the source of an ElementTree as a string in Python?

2 Answers 2

9
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
  • 'ElementTree' object has no attribute 'tostring' happens when I tried this
    – James
    Nov 23, 2012 at 17:00
  • @James: then you are calling it on the wrong object. It's the module that has that method.
    – Martijn Pieters
    Nov 23, 2012 at 17:03
  • @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).
    – unutbu
    Nov 23, 2012 at 17:05
  • @MartijnPieters Yes! Thank you for pointing that out. I will accept as soon as I can
    – James
    Nov 23, 2012 at 17:06
0

I know it is not, but I wonder why it wouldn't be:

tree.tostring(root)

instead of the current way:

xml.etree.ElementTree.tostring(root)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.