How would you get the source of an ElementTree
as a string in Python?
Get string source of Python xml ElementTree
Asked Answered
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)
.
'ElementTree' object has no attribute 'tostring' happens when I tried this –
Liberate
@James: then you are calling it on the wrong object. It's the module that has that method. –
Disbelieve
@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)
. –
Albertinaalbertine @MartijnPieters Yes! Thank you for pointing that out. I will accept as soon as I can –
Liberate
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)
© 2022 - 2024 — McMap. All rights reserved.