-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathXmlToJsonConverter.py
71 lines (63 loc) · 2.98 KB
/
XmlToJsonConverter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import json
import os
from xml.dom import minidom
from xml.parsers import expat
import xmltodict
from termcolor import colored
class XmlToJson:
def __init__(self, xmlFilePath: any = "D:/xmlfile", jsonFilePath: any = "D:/jsonfile"):
self.xmlFile = []
self.xmlFilePath = xmlFilePath # path of xml file
self.jsonFilePath = jsonFilePath # path of json file where json file will be created
self.getjson() # call getjson function
def convertXMLFileToList(self):
# for handle the exception using try and case
try:
for root, dirs, files in os.walk(self.xmlFilePath):
for file in files:
if file.endswith('.xml'):
self.xmlFile.append(file)
return self.xmlFile
except FileNotFoundError: # This is skipped if file exists
print("FileNotFoundError")
except Exception as e: # This is processed instead
print("An exception occurred: ", e)
finally: # This is always processed no matter what
pass
def getjson(self):
# this function is to convert xml file to json file
try:
for filename in self.convertXMLFileToList(): # call function to read xml file
with open(self.xmlFilePath + '/' + filename, 'r') as f: # read XML file one by one
xml = f.read()
xml = minidom.parseString(xml)
xml = xml.toprettyxml()
xml = xmltodict.parse(xml, attr_prefix='', encoding='utf-8', expat=expat)
baseFileName = filename.split('.xml')[0]
with open(self.jsonFilePath + '/' + baseFileName + '.json', 'w') as f:
json.dump(xml, f, indent=4)
self.clean_clm_file(baseFileName + '.json')
print(colored(f"Total {len(self.xmlFile)} files Successfully converted XML to JSON", 'green'))
except FileNotFoundError: # This is skipped if file exists
print("FileNotFoundError")
except Exception as e: # This is processed instead
print("An exception occurred: ", e)
finally: # This is always processed no matter what
pass
def clean_clm_file(self, file):
with open(self.jsonFilePath + "/" + file, 'r') as f:
data = json.load(f)
data = json.dumps(data, indent=4)
data = data.replace("\\t", "")
data = data.replace("\\n", "")
data = data.replace("#", "")
data = data.replace("ns0:", "")
data = data.replace("ns2:", "")
data = data.replace("xsi:", "")
data = data.replace("pat:", "")
data = data.replace("com:", "")
data = json.loads(data)
with open(self.jsonFilePath + "/" + file, 'w') as f:
json.dump(data, f, indent=4)
if __name__ == '__main__':
XmlToJson() # XmlToJson("D:/xmlfile", "D:/jsonfile")