@@ -69,10 +69,10 @@ def load_xml(filename: str):
69
69
"""
70
70
with open (filename , "rb" ) as infile :
71
71
tree = ET .parse (infile ) # Parse the XML file into an ElementTree object
72
- root = tree .getroot () # Get the root element
72
+ root = tree .getroot () # Get the root element
73
73
74
74
# Convert the ElementTree object to a dictionary
75
- data = element_to_dict (root )
75
+ data = { root . tag : element_to_dict (root )}
76
76
77
77
return convert_values (data )
78
78
@@ -87,18 +87,21 @@ def element_to_dict(element):
87
87
Returns:
88
88
The converted dictionary.
89
89
"""
90
- if len (element ) == 0 :
91
- return element .text
92
-
93
90
result = {}
94
- for child in element :
95
- child_data = element_to_dict (child )
96
- if child .tag in result :
97
- if not isinstance (result [child .tag ], list ):
98
- result [child .tag ] = [result [child .tag ]]
99
- result [child .tag ].append (child_data )
91
+ attrs = element .attrib
92
+ if attrs :
93
+ result .update (attrs )
94
+
95
+ for child_element in element :
96
+ child_key = child_element .tag
97
+ child_value = element_to_dict (child_element )
98
+
99
+ if child_key in result :
100
+ if not isinstance (result [child_key ], list ):
101
+ result [child_key ] = [result [child_key ]]
102
+ result [child_key ].append (child_value )
100
103
else :
101
- result [child . tag ] = child_data
104
+ result [child_key ] = child_value
102
105
103
106
return result
104
107
0 commit comments