#!/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 ') #注意是二进制写入, otherwise there will be extra spaces
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!")
Using Python for XML to CSV