-
Notifications
You must be signed in to change notification settings - Fork 1
/
parse_xml.py
54 lines (41 loc) · 1.85 KB
/
parse_xml.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
"""
Small script to parse an XML file and print the contents, focusing on type.
"""
import xmltodict
def traverse(current: object, depth: int = 2, current_depth: int = -1, key: str = ''):
"""
Given a structured list/tree representing an XML file, iterates through to print it
to a specified depth. Importantly, shows the datatypes.
:param current: The current tree entry- may be an endpoint, or something that branches further.
:param depth: The maximum number of dictionaries or lists to delve into.
:param current_depth: The depth of the current iteration.
:param key: If this object was an entry in a dictionary, what was its key?
:return: None
"""
current_depth += 1
if isinstance(current, list):
print(' ' * current_depth + key + str(type(current)) + ': [')
if current_depth < depth:
for item in current:
traverse(item, depth, current_depth)
else:
print(' ' * current_depth + " <MAX DEPTH REACHED>")
print(' ' * current_depth + ']')
elif isinstance(current, dict):
print(' ' * current_depth + key + str(type(current)) + ': {') # Not using f-strings as they hate loose {
if current_depth < depth:
for key, value in current.items():
traverse(value, depth, current_depth, key)
else:
print(' ' * current_depth + " <MAX DEPTH REACHED>")
print(' ' * current_depth + '}')
else:
print(' '*current_depth + key + str(type(current)) + ': ' + str(current))
with open('helentest.xml') as input_file:
print(f"### {input_file.name} ###")
tree = xmltodict.parse(input_file.read())
traverse(tree, depth=5)
with open('pta_combined_test.xml') as input_file:
print(f"### {input_file.name} ###")
tree = xmltodict.parse(input_file.read())
traverse(tree, depth=6)