利用Python进行XML转CSV
#!/usr/bin/python
#XMLtoCSV.py
#encoding:utf-8
import csv, os
from xml.dom.minidom import parse
def createCSVFile(filePrefix):
csvFile = open(filePrefix+'.csv', 'wb') #注意是二进制写入,否则会有多余空格
csvWriter = csv.writer(csvFile)
bWriteHead = False
xmlFile = open(filePrefix+'.xml')
domTree = parse(xmlFile)
#print domTree
root = domTree.documentElement
#print dir(collection)
for node in root.childNodes:
if node.nodeType == node.ELEMENT_NODE:
#print node.nodeName
element = {}
for key in node.attributes.keys():
value = node.attributes.get(key).value
element[key] = value
if len(element) > 0:
if bWriteHead == False:
csvWriter.writerow(tuple(element.keys()))
bWriteHead = True
csvWriter.writerow(tuple(element.values()))
else:
print node.attributes
csvFile.close()
xmlFile.close()
def main():
for root, dirs, files in os.walk(os.getcwd()):
print root, dirs, files
for fname in files:
index = fname.find('.xml')
if index > 0:
#print index, fname[:index]
createCSVFile(fname[:index])
print "TransfORM " + fname + " OK!"
if __name__ == '__main__':
main()
input("Game Over!")
相关文章