I am trying to create a xml file from a csv
CSV:
CatOne, CatTwo, CatThree
ProdOne, ProdTwo, ProdThree
ProductOne, ProductTwo, ProductThree
Desired XML:
<root>
<prod>
<CatOne>ProdOne</CatOne>
<CatTwo>ProdTwo</CatTwo>
<CatThree>ProdThree</CatThree>
</prod>
<prod>
<CatOne>ProductOne</CatOne>
<CatTwo>ProductTwo</CatTwo>
<CatThree>ProductThree</CatThree>
</prod>
</root>
Here is my code:
#! usr/bin/python
# -*- coding: utf-8 -*-
import csv, sys, os
from lxml import etree
def main():
csvFile = 'test.csv'
xmlFile = open('myData.xml', 'w')
csvData = csv.reader(open(csvFile), delimiter='\t')
header = csvData.next()
details = csvData.next()
details2 = csvData.next()
root = etree.Element('root')
prod = etree.SubElement(root,'prod')
for index in range(0, len(header)):
child = etree.SubElement(prod, header[index])
child.text = details[index]
prod.append(child)
prod = etree.SubElement(root,'prod')
for index in range(0, len(header)):
child = etree.SubElement(prod, header[index])
child.text = details2[index]
prod.append(child)
result = etree.tostring(root, pretty_print=True)
xmlFile.write(result)
if __name__ == '__main__':
main()
I am getting the desired output, but the way I am doing it, is really shitty. I'd like to have it in some generic way and I believe it is possible much more pythonic But I can't figure out how to do this. The code should also work, if the csv has 10 or even 20 lines.
Thanks for help