Python ImportError:没有名为elementtree.SimpleXMLWriter的模块
在python代码中,我试图以XML格式显示输出 但它显示出错误:Python ImportError:没有名为elementtree.SimpleXMLWriter的模块,python,xml,elementtree,xmlwriter,Python,Xml,Elementtree,Xmlwriter,在python代码中,我试图以XML格式显示输出 但它显示出错误: 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
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
我的整个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()
我不是一个使用XML的向导,但是,它看起来要么需要安装(显然是SimpleXMLWriter…也许它从未被拉入标准库),要么使用标准库中的工具 在我看来,这就像:
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()
编写此文件
Python 2.5及更高版本附带的
ElementTree
模块不包括SimpleXMLWriter
模块;后者完全独立于ElementTree
功能的其余部分
为了生成XML,我个人使用了一种模板语言,如。您还可以使用ElementTree API本身构建树,并对结果调用
.write()
。您的环境中是否安装了ElementTree
模块?我想您需要安装。您使用的是哪一版本的python?此错误表示未安装elementtree。这是哪个操作系统?我使用的是windows vista(64位)…python版本是2.7
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])