Skip to content

Instantly share code, notes, and snippets.

@Stevoisiak
Created March 5, 2018 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Stevoisiak/23ed3f7ea643060128f296313f05b7df to your computer and use it in GitHub Desktop.
Save Stevoisiak/23ed3f7ea643060128f296313f05b7df to your computer and use it in GitHub Desktop.

Converting ElementTree to string raises "TypeError: argument of type 'int' is not iterable"

I have a simple XML element created with xml.etree.ElementTree in Python 3. This element contains a person's name and age.

import xml.etree.ElementTree as ElementTree
person = ElementTree.Element("Person", Name="John", Age=18)

I can use Element.get() to access individual attributes from my element without any issues.

import xml.etree.ElementTree as ElementTree
person = ElementTree.Element("Person", Name="John", Age=18)

name = person.get("Name")
age = person.get("Age")
print(name + " is " + str(age) + " years old.")
# output: "John is 18 years old"

However, trying to use .tostring() to retrieve my element as a string raises "TypeError: argument of type 'int' is not iterable"

import xml.etree.ElementTree as ElementTree
person = ElementTree.Element("Person", Name="John", Age=18)

print(ElementTree.tostring(person))

Why can't I use .tostring() on an xml.etree.ElementTree.Element with an integer attribute?


Full traceback:

Traceback (most recent call last):
  File "C:\Users\svascellar\AppData\Local\Programs\Python\Python36-32\lib\xml\etree\ElementTree.py", line 1079, in _escape_attrib
    if "&" in text:
TypeError: argument of type 'int' is not iterable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/svascellar/.PyCharmCE2017.3/config/scratches/scratch_13.py", line 5, in <module>
    print(ElementTree.tostring(person))
  File "C:\Users\svascellar\AppData\Local\Programs\Python\Python36-32\lib\xml\etree\ElementTree.py", line 1135, in tostring
    short_empty_elements=short_empty_elements)
  File "C:\Users\svascellar\AppData\Local\Programs\Python\Python36-32\lib\xml\etree\ElementTree.py", line 776, in write
    short_empty_elements=short_empty_elements)
  File "C:\Users\svascellar\AppData\Local\Programs\Python\Python36-32\lib\xml\etree\ElementTree.py", line 933, in _serialize_xml
    v = _escape_attrib(v)
  File "C:\Users\svascellar\AppData\Local\Programs\Python\Python36-32\lib\xml\etree\ElementTree.py", line 1102, in _escape_attrib
    _raise_serialization_error(text)
  File "C:\Users\svascellar\AppData\Local\Programs\Python\Python36-32\lib\xml\etree\ElementTree.py", line 1057, in _raise_serialization_error
    "cannot serialize %r (type %s)" % (text, type(text).__name__)
TypeError: cannot serialize 18 (type int)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment