如何使用minidom从非字符串数据类型生成XML?
我想知道如何用minidom从非字符串的数据类型生成xml。我感觉有人会告诉我先把它们转换成字符串,但我并不是这个意思。
from datetime import datetime
from xml.dom.minidom import Document
num = "1109"
bool = "false"
time = "2010-06-24T14:44:46.000"
doc = Document()
Submission = doc.createElement("Submission")
Submission.setAttribute("bool",bool)
doc.appendChild(Submission)
Schedule = doc.createElement("Schedule")
Schedule.setAttribute("id",num)
Schedule.setAttribute("time",time)
Submission.appendChild(Schedule)
print doc.toprettyxml(indent=" ",encoding="UTF-8")
这是结果:
<?xml version="1.0" encoding="UTF-8"?>
<Submission bool="false">
<Schedule id="1109" time="2010-06-24T14:44:46.000"/>
</Submission>
我该如何获得非字符串数据类型的有效xml表示呢?
from datetime import datetime
from xml.dom.minidom import Document
num = 1109
bool = False
time = datetime.now()
doc = Document()
Submission = doc.createElement("Submission")
Submission.setAttribute("bool",bool)
doc.appendChild(Submission)
Schedule = doc.createElement("Schedule")
Schedule.setAttribute("id",num)
Schedule.setAttribute("time",time)
Submission.appendChild(Schedule)
print doc.toprettyxml(indent=" ",encoding="UTF-8")
在文件 "C:\Python25\lib\xml\dom\minidom.py" 的第299行,出错了: data = data.replace("&", "&").replace("<", "<") 出现了AttributeError: 'bool'对象没有'replace'这个属性。
1 个回答
3
绑定的方法 setAttribute
希望它的第二个参数,也就是值,是一个字符串。你可以通过把数据转换成字符串来帮助这个过程:
bool = str(False)
或者,在调用 setAttribute
时直接转换成字符串:
Submission.setAttribute("bool",str(bool))
(当然,num
和 time
也必须这样处理)。