Get string source of Python xml ElementTree
Asked Answered
L

2

10

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

Liberate answered 23/11, 2012 at 16:55 Comment(0)
A
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).

Albertinaalbertine answered 23/11, 2012 at 16:58 Comment(4)
'ElementTree' object has no attribute 'tostring' happens when I tried thisLiberate
@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 canLiberate
M
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)
Mammillary answered 7/4, 2019 at 11:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.