Skip to content

Commit a3ad919

Browse files
modified the element_to_dict function
1 parent c2e6d21 commit a3ad919

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

src/modelspec/utils.py

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -69,10 +69,10 @@ def load_xml(filename: str):
6969
"""
7070
with open(filename, "rb") as infile:
7171
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
7373

7474
# Convert the ElementTree object to a dictionary
75-
data = element_to_dict(root)
75+
data = {root.tag: element_to_dict(root)}
7676

7777
return convert_values(data)
7878

@@ -87,18 +87,21 @@ def element_to_dict(element):
8787
Returns:
8888
The converted dictionary.
8989
"""
90-
if len(element) == 0:
91-
return element.text
92-
9390
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)
100103
else:
101-
result[child.tag] = child_data
104+
result[child_key] = child_value
102105

103106
return result
104107

0 commit comments

Comments
 (0)