Skip to content
Advertisement

Convert Python ElementTree to string

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 a str object, you have two options:

    1. Decode the resulting bytes value, from UTF-8: xmlstr.decode("utf8")

    2. 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. Use utf-8 or UTF-8 (with a dash) if you want to prevent this. When using encoding="unicode" no declaration header is added.

Advertisement