I am currently working on a SQL databse in Python. I want to write my data from the database to an XML file with the library from ElementTree
. I've read all Stackoverflow solutions for my problem but none of them worked for me. My problem is that the data which comes from the database keeps the same. My code looks like this:
sql_cmd = "SELECT" + rows + "FROM" + tables + \
"WHERE queue.id = ticket.queue_id AND ticket.id = article.ticket_id LIMIT 100;"
ticket = ElementTree.Element("ticket")
tree = ElementTree.ElementTree()
tree._setroot(ticket)
for data in db():
customer_id = ElementTree.Element("customer_id")
ticket_id = ElementTree.Element("ticket_id")
article_id = ElementTree.Element("article_id")
customer_id.text = str(data[0])
ticket_id.text = str(data[1])
article_id.text = str(data[2])
ticket.append(article_id)
ticket.append(ticket_id)
ticket.append(customer_id)
tree.write("data.xml", encoding="utf8")
The str(data[0])
and so on is the data from my DB. If i run my code like this everything works but it keeps repeating the same XML structure with the same values. On My SQL command i set a limit which is 100. db()
is my function where my data gets returned. I iterate over it in the for loop.
I have also tried to use
with open('data.xml', 'a') as f:
tree.write(f)
but that didnt worked either. The error was:
TypeError: write() argument must be str, not bytes
Can Somebody tell me what's my issue and how to fix it? Thanks.