Skip to content
Advertisement

Convert Python ElementTree to string

Whenever I call ElementTree.tostring(e), I get the following error message:

JavaScript

Is there any other way to convert an ElementTree object into an XML string?

TraceBack:

JavaScript

Advertisement

Answer

Element objects have no .getroot() method. Drop that call, and the .tostring() call works:

JavaScript

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:

      JavaScript
  • 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