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).

Sign up to request clarification or add additional context in comments.

4 Comments

'ElementTree' object has no attribute 'tostring' happens when I tried this
@James: then you are calling it on the wrong object. It's the module that has that method.
@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).
@MartijnPieters Yes! Thank you for pointing that out. I will accept as soon as I can
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)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.