4

In my python code I am trying to display the output in a XML format.For this purpose I am using XMLwriter.

But it is showing error:

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

The line which causes the error is:

from elementtree.SimpleXMLWriter import XMLWriter

My entire python code is:

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()
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
prakash .k
  • 635
  • 2
  • 12
  • 24

2 Answers2

3

The ElementTree module as shipped with Python 2.5 and up does not include the SimpleXMLWriter module; the latter is entirely separate from the rest of the ElementTree functionality.

To generate XML, I personally use a templating language such as Chameleon. You can also build the tree by using the ElementTree API itself and simply call .write() on the result.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

I'm not a wizard with XML, however, it looks like you either need to install elementtree (apparently SimpleXMLWriter wasn't included in python2.5 ... and maybe it's never been pulled into the standard library), or use the facilities in the standard library.

To me, it looks like something like:

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

You can then write this using root.write().

reference1

reference2

mgilson
  • 300,191
  • 65
  • 633
  • 696