Creating xml from MySQL query with Python and lxml

2024/10/6 9:10:57

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 MySQLdbtry: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 = 0for column in columns:data = rows[columnNumber]if data == None:data = ''xmlFile.write('<%s>%s</%s>' % (column,data,column))columnNumber += 1xmlFile.write('</ROW>')
xmlFile.write('</DATA>')
xmlFile.close()
Answer

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 buildEclass 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.datadef 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 elementdef 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 docdoc = 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>
https://en.xdnf.cn/q/119512.html

Related Q&A

How to add another iterator to nested loop in python without additional loop?

I am trying to add a date to my nested loop without creating another loop. End is my list of dates and end(len) is equal to len(year). Alternatively I can add the date to the dataframe (data1) is that …

How to know where the arrow ends in matplotlib quiver

I have programmed plt.quiver(x,y,u,v,color), where there are arrows that start at x,y and the direction is determined by u,v. My question is how can I know exactly where the arrow ends?

how send text(sendkey) to ckeditor in selenium python scripting -chrome driver

I cant send a text to the text box of CKEditor while I scripting.it not shown in the seleniumIDE recording also.Help me to fix this issueASAP

How to replace the column of dataframe based on priority order?

I have a dataframe as follows df["Annotations"] missense_variant&splice_region_variant stop_gained&splice_region_variant splice_acceptor_variant&coding_sequence_variant&intron…

Scraping from web page and reformatting to a calender file

Im trying to scrape this site: http://stats.swehockey.se/ScheduleAndResults/Schedule/3940And Ive gotten as far (thanks to alecxe) as retrieving the date and teams.from scrapy.item import Item, Field fr…

Python Text to Data Frame with Specific Pattern

I am trying to convert a bunch of text files into a data frame using Pandas. Thanks to Stack Overflows amazing community, I almost got the desired output (OP: Python Text File to Data Frame with Specif…

Python Multiprocess OpenCV Webcam Get Request [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

error when trying to run my tensorflow code

This is a follow up question from my latest post: Put input in a tensorflow neural network I precoded a neural network using tensorflow with the MNIST dataset, and with the help of @FinnE was able to c…

ValueError: invalid literal for int() with base 10: Height (mm)

import csv from decimal import *def mean(data_set):return Decimal(sum(data_set)) / len(data_set)def variance(data_set):mean_res = mean(data_set)differences = []squared_res = []for elem in data_set:diff…

Having trouble in getting page source with beautifulsoup

I am trying to get the HTML source of a web page using beautifulsoup. import bs4 as bs import requests import urllib.request sourceUrl=https://www.pakwheels.com/forums/t/planing-a-trip-from-karachi-to-…