给定元素的xml.etree.ElementTree.write()整数值可以吗? [英] can xml.etree.ElementTree.write() integer values for a given Element?

查看:193
本文介绍了给定元素的xml.etree.ElementTree.write()整数值可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

冒着被问到这样简单的问题而大喊大叫的风险,但是我一直在互联网上寻找答案,这种特殊情况似乎被广泛避免,并且文档也模棱两可:

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:

是否可以使用xml.etree.ElementTree.write()在元素的属性中写入非字符串值?
我总是得到:

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.

干杯,
坦白

推荐答案

与XML数据相反,XML属性是文本。 http://www.w3schools.com/xml/xml_attributes.asp

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

由您决定在xml序列化之前将属性序列化为字符串。

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

这篇关于给定元素的xml.etree.ElementTree.write()整数值可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆