can xml.etree.ElementTree.write() integer values for a given Element?
Asked Answered
L

1

6

at the risk of getting yelled at for asking such a simple question, but I have been trawling the internet for answers and this particular case seems to be widely avoided and the docs are ambiguous:

Is it possible to use xml.etree.ElementTree.write() to write non-string values in an element's attribute? I always get:

TypeError: cannot serialize 0 (type int)

when I try something like this:

root = ET.Element('Tasks')
d = {'priority': 1, 'status': 0, 'name': 'new task', 'index': 0}
d = ET.SubElement(root, 'Settings', attrib=d)
tree = ET.ElementTree(root)
tree.write('/tmp/xmlTest')

I have been working around it several times by iterating over the respective dictionary and turning all values into strings first, but that doesn't feel right and before I botch it again I would like to know how it should be done properly as to not get used to a bad habit. So any insight would be much appreciated.

Cheers, frank

Longeron answered 23/10, 2013 at 6:24 Comment(0)
M
13

In contrast with XML data, XML attributes are texts. http://www.w3schools.com/xml/xml_attributes.asp

It is up to you to serialize attributes to strings before xml serialization.

Multiplication answered 23/10, 2013 at 6:44 Comment(1)
Sure, because it is a rocket science to serialize integer type. Well done, Python ! However, thanks for the answer, it was really helpful :).Willumsen

© 2022 - 2024 — McMap. All rights reserved.