#!/usr/bin/python#csvtoxml.py#encoding:utf-8import csv, osfrom xml.dom.minidom import Document#prfixFile = "Creature_data" Def createxmlfile (fileprefix): csvfile = open (fileprefix+ '. csv '); headline = Csvfile.readline () #print headLine typeList = Headline.split (', ') doc = document () dataroot = doc.createelement (fileprefix+ ' List ') dataroot.setattribute (' Xmlns:xsi ', " Http://www.w3.org/2001/XMLSchema-instance ") dataroot.setattribute (' Xsi:schemalocation ', fileprefix+ '. xsd ') doc.appendchild (dataRoot) csvreader = csv.reader (CSVFile) for line in csvReader: #print line dataelt = doc.createelement (FilePrefix) for i in range (Len (typelist)): dataelt.setattribute (Typelist[i], line[i]) dataroot.appendchild (Dataelt) xmlFile = Open (fileprefix+ '. xml ', ' W ') xmlfile.write (doc.toprettyxml (indent = ' \ t ')) xmlfile.close () Def main (): for root, dirs, Files in os.walk (OS.GETCWD ()): for fname in files: index = Fname.find ('. csv ') if index > 0: #print index, fname[: index] Createxmlfile (Fname[:index]) print "transform " + fname + " ok!" if __name__ == ' __main__ ': main () input ("Game over! ")
CSV to XML using Python