2017-01-05 15 views
0

PostgreSQLデータベーステーブルからXMLファイルを生成しようとしています。私は以下のコードを使用して生成することができましたが、フォーマットされず、1行で表示されます。行から行を取得している間、完全なファイルが1行に表示されます。どうすればこの問題を解決できますか?PSQLデータベーステーブルからXMLファイルを生成するPythonスクリプト

def tableToXML(message): 
    conn = None 
    try: 
     conn=psycopg2.connect("dbname='DB' user='user' password='i123456'") 
    except: 
     print "I am unable to connect to the database." 

    cur = conn.cursor() 
    try: 
     cur.execute("SELECT table_to_xml('usapp_sipconf', true, false, '')") 
    except: 
     print "I can't SELECT from sipconf" 

    rows = cur.fetchall() 
    with open('sipconf.xml', 'w') as f: 
     for row in rows: 
      print row 
      f.write("%s" % (str(row))) 
    if conn: 
     conn.close() 
    return True 
+0

問題ありません。 XMLは依然として有効で整形式ですが、人間の可読性のために改行や字下げがありません。かなりの出力を出力するPythonモジュールを探してください。 – Parfait

答えて

0

私は前にthses変更を加えることで、PostgreSQLデータベーステーブルからXMLファイルを生成しています既存のコード。

def tableToXML(tableName): 
    conn  = None 
    columnList = [] 
    fileName = 'usappxml/'+tableName+'.xml' 
    message = '<'+tableName+'>\n' 

    try: 
     conn = psycopg2.connect("dbname='db' user='dbuser' password='123456'") 
    except: 
     print " *** Can't able to connect database. *** " 
     return False 

    outfile = file(fileName, 'w') 
    cursor = conn.cursor() 

    cursor.execute("SELECT column_name from information_schema.columns where table_name = '%s'" % tableName) 
    columns = cursor.fetchall() 

    for column in columns: 
     columnList.append(column[0]) 

    cursor.execute("select * from %s" % tableName) 
    rows = cursor.fetchall() 

    outfile.write('<?xml version="1.0" ?>\n') 
    outfile.write(message) 
    for row in rows: 
     outfile.write(' <row>\n') 
     for i in range(len(columnList)): 
      outfile.write(' <%s>%s</%s>\n' % (columnList[i], row[i], columnList[i])) 
      outfile.write(' <%s>%s</%s>\n' % (columnList[i], row[i], columnList[i])) 
     outfile.write(' </row>\n') 
    outfile.write(message) 

    outfile.close() 
    return True 
関連する問題