Using Python for XML to CSV

Source: Internet
Author: User

#!/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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.