Whenever I call ElementTree.tostring(e)
, I get the following error message:
AttributeError: 'Element' object has no attribute 'getroot'
Is there any other way to convert an ElementTree object into an XML string?
TraceBack:
Traceback (most recent call last): File "Development/Python/REObjectSort/REObjectResolver.py", line 145, in <module> cm = integrateDataWithCsv(cm, csvm) File "Development/Python/REObjectSort/REObjectResolver.py", line 137, in integrateDataWithCsv xmlstr = ElementTree.tostring(et.getroot(),encoding='utf8',method='xml') AttributeError: 'Element' object has no attribute 'getroot'
Advertisement
Answer
Element
objects have no .getroot()
method. Drop that call, and the .tostring()
call works:
xmlstr = ElementTree.tostring(et, encoding='utf8', method='xml')
You only need to use .getroot()
if you have an ElementTree
instance.
Other notes:
This produces a bytestring, which in Python 3 is the
bytes
type.
If you must have astr
object, you have two options:Decode the resulting bytes value, from UTF-8:
xmlstr.decode("utf8")
Use
encoding='unicode'
; this avoids an encode / decode cycle:xmlstr = ElementTree.tostring(et, encoding='unicode', method='xml')
If you wanted the UTF-8 encoded bytestring value or are using Python 2, take into account that ElementTree doesn’t properly detect
utf8
as the standard XML encoding, so it’ll add a<?xml version='1.0' encoding='utf8'?>
declaration. Useutf-8
orUTF-8
(with a dash) if you want to prevent this. When usingencoding="unicode"
no declaration header is added.