forked from Apress/practical-ml-w-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathread_xml.py
More file actions
122 lines (93 loc) · 3.16 KB
/
read_xml.py
File metadata and controls
122 lines (93 loc) · 3.16 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# -*- coding: utf-8 -*-
"""
Created on Wed May 10 19:51:47 2017
@author: Raghav Bali
"""
"""
This script showcases methods to read XML type data using:
+ powerful xml library
+ xml to dict
``Execute``
$ python read_xml.py
"""
import xml.etree.ElementTree as ET
import xmltodict
def print_nested_dicts(nested_dict,indent_level=0):
"""This function prints a nested dict object
Args:
nested_dict (dict): the dictionary to be printed
indent_level (int): the indentation level for nesting
Returns:
None
"""
for key, val in nested_dict.items():
if isinstance(val, dict):
print("{0} : ".format(key))
print_nested_dicts(val,indent_level=indent_level+1)
elif isinstance(val,list):
print("{0} : ".format(key))
for rec in val:
print_nested_dicts(rec,indent_level=indent_level+1)
else:
print("{0}{1} : {2}".format("\t"*indent_level,key, val))
def print_xml_tree(xml_root,indent_level=0):
"""This function prints a nested dict object
Args:
xml_root (dict): the xml tree to be printed
indent_level (int): the indentation level for nesting
Returns:
None
"""
for child in xml_root:
print("{0}tag:{1}, attribute:{2}".format(
"\t"*indent_level,
child.tag,
child.attrib))
print("{0}tag data:{1}".format("\t"*indent_level,
child.text))
print_xml_tree(child,indent_level=indent_level+1)
def read_xml(file_name):
"""This function extracts and prints XML content from a given file
Args:
file_name (str): file path to be read
Returns:
None
"""
try:
tree = ET.parse(file_name)
root = tree.getroot()
print("Root tag:{0}".format(root.tag))
print("Attributes of Root:: {0}".format(root.attrib))
print_xml_tree(root)
except IOError:
raise IOError("File path incorrect/ File not found")
except Exception:
raise
def read_xml2dict_xml(file_name):
"""This function extracts and prints xml content from a file using xml2dict
Args:
file_name (str): file path to be read
Returns:
None
"""
try:
xml_filedata = open(file_name).read()
ordered_dict = xmltodict.parse(xml_filedata)
print_nested_dicts(ordered_dict)
except IOError:
raise IOError("File path incorrect/ File not found")
except ValueError:
ValueError("XML file has errors")
except Exception:
raise
if __name__=='__main__':
print("\n\n")
print("*"*30)
print("Contents of sample xml file:")
print("*"*30)
read_xml(r'sample_xml.xml')
print("\n\n")
print("*"*30)
print("Contents of a xml file using xml2dict:")
print("*"*30)
read_xml2dict_xml(r'sample_xml.xml')