Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7783405
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T19:49:47+00:00 2026-06-01T19:49:47+00:00

I am trying to use Python and LXML to create an XML file from

  • 0

I am trying to use Python and LXML to create an XML file from a Mysql query result. Here is the format I want.

     <DATA>
         <ROW>
             <FIELD1>content</FIELD1>
             <FIELD2>content</FIELD2>
         </ROW>
    </DATA>

For some reason the code isn’t formatting right and the XML will not validate. Here is that code

from lxml import etree
from lxml.etree import tostring
from lxml.builder import E
import MySQLdb


try:
       conn = MySQLdb.connect(host = 'host',user = 'user',passwd = 'pass',db = 'db')
       cursor = conn.cursor()
except:
       sys.exit(1)

cursor.execute("SELECT * FROM db.table")
columns = [i[0] for i in cursor.description]
allRows = cursor.fetchall()
xmlFile = open("mysqlxml.xml","w")
xmlFile.write('<DATA>')
for rows in allRows:
       xmlFile.write('<ROW>')
       columnNumber = 0
       for column in columns:
              data = rows[columnNumber]
              if data == None:
                     data = ''
              xmlFile.write('<%s>%s</%s>' % (column,data,column))
              columnNumber += 1
       xmlFile.write('</ROW>')
xmlFile.write('</DATA>')
xmlFile.close()
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T19:49:49+00:00Added an answer on June 1, 2026 at 7:49 pm

    Here’s a little example of how you can build xml using lxml.

    It’s useful to create a helper function for element creation, here’s a simple one. I’ve created a dummy cursor object for demo purposes.

    from lxml import etree
    from lxml.builder import E as buildE
    
    class DummyCursor(object):
      def __init__(self,fields,rows=5):
        self.description = [[f] for f in fields]
        self.data = [ ["%s%02d" % (f,i) for f in fields] for i in range(rows) ]
      def fetchall(self):
        return self.data
    
    def E(tag,parent=None,content=None):
      """Simple E helper"""
      element = buildE(tag)
      if content is not None:
        element.text = unicode(content)
      if parent is not None:
        parent.append(element)
      return element
    
    def fetchXML(cursor):
      fields = [x[0] for x in cursor.description ]
      doc = E('data')
      for record in cursor.fetchall():
        r = E('row',parent=doc)
        for (k,v) in zip(fields,record):
          E(k,content=v,parent=r)
      return doc
    
    doc = fetchXML(DummyCursor(['name','description']))
    
    print etree.tostring(doc,pretty_print=True)
    

    Yields:

    <data>
      <row>
        <name>name00</name>
        <description>description00</description>
      </row>
      <row>
        <name>name01</name>
        <description>description01</description>
      </row>
      <row>
        <name>name02</name>
        <description>description02</description>
      </row>
      <row>
        <name>name03</name>
        <description>description03</description>
      </row>
      <row>
        <name>name04</name>
        <description>description04</description>
      </row>
    </data>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to use Python 2.7 regex's to retrieve data from sample web pages
I am trying to use Pythons LXML library to create a GPX file that
I am trying to use Python to read in an XML file containing some
I'm trying to use Python's xml.dom.minidom, and I'm getting the following error: >>> from
I'm trying to use Python to download a voice file (mp3) from this site:
I am trying to use Python in order to manipulate a text file from
I'm trying to use python to parse a log file and match 4 pieces
I am trying to use Python's ElementTree to generate an XHTML file. However, the
I am trying to use python socket instead of netcat to send metric data
I am trying to use python's telnetlib module to get information from a remote

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.