开发者

How do you generate xml from non string data types using minidom?

How do you generate xml from non string data types using minidom? I have a feeling someone is going to tell me to generate strings before hand, but this is not what I'm after.

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)
Schedu开发者_StackOverflow中文版le.setAttribute("time",time)
Submission.appendChild(Schedule)

print doc.toprettyxml(indent="  ",encoding="UTF-8")

This is the result:

<?xml version="1.0" encoding="UTF-8"?>
<Submission bool="false">
  <Schedule id="1109" time="2010-06-24T14:44:46.000"/>
</Submission>

How do I get valid xml representations of non-string datatypes?

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")

File "C:\Python25\lib\xml\dom\minidom.py", line 299, in _write_data data = data.replace("&", "&").replace("<", "<") AttributeError: 'bool' object has no attribute 'replace'


The bound method setAttribute expects its second argument, the value, to be a string. You can help the process along by converting the data to strings:

bool = str(False)

or, converting to strings when you call setAttribute:

Submission.setAttribute("bool",str(bool))

(and of course, the same must be done for num and time).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜