如何使用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")
_write_data中的文件“C:\ Python25 \ lib \ xml \ dom \ minidom.py”,第299行 data = data.replace(“&amp;”,“&amp;”)。replace(“&lt;”,“&lt;”) AttributeError:'bool'对象没有属性'replace'
答案 0 :(得分:3)
绑定方法setAttribute
期望其第二个参数值为字符串。您可以通过将数据转换为字符串来帮助完成此过程:
bool = str(False)
或在致电setAttribute
时转换为字符串:
Submission.setAttribute("bool",str(bool))
(当然,num
和time
也必须这样做。