[XML-SIG] How to convert my data in database to XML
Malcolm Tredinnick
malcolm at commsecure.com.au
Thu Nov 4 00:34:45 CET 2004
On Wed, 2004-11-03 at 15:05 -0800, Dave Kuhlman wrote:
[...]
> Here is the trivial example:
>
> import psycopg
>
> CONNECT_ARGS = 'host=localhost user=postgres1 password=mypassword dbname=test'
>
> def exportPlants(outfileName):
> outfile = file(outfileName, 'w')
> connection = psycopg.connect(CONNECT_ARGS)
> cursor = connection.cursor()
> cursor.execute("select * from Plant_DB order by p_name")
> rows = cursor.fetchall()
> outfile.write('<?xml version="1.0" ?>\n')
> outfile.write('<mydata>\n')
> for row in rows:
> outfile.write(' <row>\n')
> outfile.write(' <name>%s</name>\n' % row[0])
> outfile.write(' <desc>%s</desc>\n' % row[1])
> outfile.write(' <rating>%s</rating>\n' % row[2])
> outfile.write(' </row>\n')
> outfile.write('</mydata>\n')
> outfile.close()
Your example code will fail if the database data contains '<' or '&'
anywhere. One would need to convert these into the appropriate entity
references (< and &) first. The escape() method in
xml.sax.saxutils is pretty useful for this purpose.
Cheers,
Malcolm
More information about the XML-SIG
mailing list