Posts

Showing posts with the label Marshalling

Convert Python ElementTree To String

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