Saturday 3 January 2015

Python - Parse XML file

# ==================================================================
# >> Short Description: 
# Script searches for xml file in given root directory matching
# given pattern and prints selected file to xml
#
# >> Author: Tomas Nemeth
# >> Creation Date: 12/2014
# ==================================================================
#
#-- Import Python modules -----------
import os
import fnmatch
import sys
import xml.etree.ElementTree as ET
from xml.dom import minidom
#------------------------------------
#
#
rootPath = str(input("Insert root path: ")) # e.g. C:\Python34\Doc\ScriptTest
pattern = str(input("Insert file pattern: ")) # including wildcards, e.g. "data*"
print('=================================================')

# Search for the files matching given directory & pattern
for root, dirs, files in os.walk(rootPath):
    for filename in fnmatch.filter(files, pattern):
        print(os.path.join(root, filename)) # prints the results
#
# User is asked here to select one file from list for parsing
print('=========================================')
file = str(input("Select one file from list for parsing: "))
print('=========================================')
#
# get the root
tree = ET.parse(file)
root = tree.getroot()
#
# Function prints selected file as whole xml
xmldoc = minidom.parse(file)
print(xmldoc.toxml())
#
print('==========================================')
print('')

No comments:

Post a Comment