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

人走茶凉 提交于 2019-12-06 00:34:41

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/19534288/can-xml-etree-elementtree-write-integer-values-for-a-given-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!