导入错误:未找到elementtree.SimpleXMLWriter模块

4

在我的Python代码中,我试图以XML格式显示输出。为此,我使用了XMLwriter

但是它显示错误:

Traceback (most recent call last):
  File "C:\Users\Ponmani\Desktop\test.cgi", line 8, in <module>
    from elementtree.SimpleXMLWriter import XMLWriter
ImportError: No module named elementtree.SimpleXMLWriter

导致错误的代码行是:
from elementtree.SimpleXMLWriter import XMLWriter

我的整个Python代码如下:

import os
import cgi
import MySQLdb
import cgitb
from xml.etree.ElementTree import ElementTree
from elementtree.SimpleXMLWriter import XMLWriter
import sys
import SecureDb
cgitb.enable()
print "Content-type: text/xml\n\n";
root=xml.start("root")
conn= MySQLdb.connect(host = SecureDb.host ,user =SecureDb.user ,passwd=SecureDb.password ,db=SecureDb.database)
cursor=conn.cursor()
xml=XMLWriter(sys.stdout)
cursor.execute("select * from register where Name='Subburaj'")
result=cursor.fetchall()
if(result!=()):    
    for colns in result:
         xml.start("Group")
         xml.element("Name","%s" %(colns[0]))
         xml.element("Mail","%s" %(colns[1]))
print result
xml.end()
xml.close(root)
conn.commit()
cursor.close()
conn.close()

你的环境中是否安装了“elementtree”模块? - Ignacio Contreras Pinilla
你需要安装elementtree工具包,我认为。 - tuxuday
你使用的Python版本是哪个?这个错误表明你没有安装ElementTree。这是哪个操作系统? - oz123
我使用的是 Windows Vista(64 位)操作系统,Python 版本为 2.7。 - prakash .k
2个回答

3
Python 2.5及以上版本所附带的ElementTree模块不包括SimpleXMLWriter模块;后者与其余ElementTree功能完全独立。
要生成XML,我个人使用类似Chameleon的模板语言。您还可以使用ElementTree API构建树,然后在结果上简单调用.write()

1

我不是XML方面的专家,但看起来你需要安装elementtree(显然SimpleXMLWriter 没有包含在python2.5中...也许它从未被拉入标准库),或者使用标准库中的工具。

对我来说,这似乎像是:

import xml.etree.ElementTree as ET
root = ET.Element('root')
#...

for colns in result:
     new_group = ET.SubElement(root,"Group")
     new_elem = ET.SubElement(new_group,"Name")
     new_elem.text = "%s" %(colns[0])
     #I suppose that:
     #ET.SubElement(new_group,"Name").text = str(colns[0])
     #would work too ...
     new_elem = ET.SubElement(new_group,"Mail")
     new_elem.text = "%s" %(colns[0])

然后,您可以使用root.write()来编写此内容。

reference1

reference2


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接