Skip to content

Commit 28e270f

Browse files
added xml serialization to the utils file
1 parent d5ef7e6 commit 28e270f

File tree

1 file changed

+26
-27
lines changed

1 file changed

+26
-27
lines changed

src/modelspec/utils.py

Lines changed: 26 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import os
88
import math
99
import numpy as np
10+
import xmltodict
1011

1112
from modelspec.base_types import print_
1213
from modelspec.base_types import EvaluableExpression
@@ -72,7 +73,7 @@ def load_xml(filename: str):
7273
# Convert the ElementTree object to a dictionary
7374
data = element_to_dict(root)
7475

75-
return data
76+
return convert_values(data)
7677

7778

7879
def element_to_dict(element):
@@ -100,6 +101,28 @@ def element_to_dict(element):
100101

101102
return result
102103

104+
def convert_values(value):
105+
if isinstance(value, str):
106+
if value.isdigit():
107+
return int(value)
108+
try:
109+
return float(value)
110+
except ValueError:
111+
pass
112+
if value.lower() == "true":
113+
return True
114+
elif value.lower() == "false":
115+
return False
116+
elif value.lower() == "none":
117+
return None
118+
elif isinstance(value, dict):
119+
return {key: convert_values(val) for key, val in value.items()}
120+
elif isinstance(value, list):
121+
return [convert_values(item) for item in value]
122+
123+
return value
124+
125+
103126

104127
def save_to_json_file(info_dict, filename, indent=4):
105128

@@ -118,7 +141,7 @@ def save_to_yaml_file(info_dict, filename, indent=4):
118141
fp.write(stry)
119142

120143

121-
def save_to_xml_file(info_dict, filename, indent=4):
144+
def save_to_xml_file(info_dict, filename, indent=4, root="modelspec"):
122145
"""
123146
Save a dictionary to an XML file.
124147
@@ -128,7 +151,7 @@ def save_to_xml_file(info_dict, filename, indent=4):
128151
indent (int, optional): The number of spaces used for indentation in the XML file.
129152
Defaults to 4.
130153
"""
131-
root = ET.Element("root")
154+
root = ET.Element(root)
132155

133156
build_xml_element(root, info_dict)
134157

@@ -164,30 +187,6 @@ def build_xml_element(parent, data):
164187
parent.text = str(data)
165188

166189

167-
def _parse_xml_element(element):
168-
"""
169-
Recursively convert an XML element to a dictionary.
170-
171-
Args:
172-
element: The XML element.
173-
174-
Returns:
175-
A dictionary representing the XML element and its children.
176-
"""
177-
data = {}
178-
for child in element:
179-
if child.tag not in data:
180-
data[child.tag] = []
181-
if len(child) > 0:
182-
data[child.tag].append(_parse_xml_element(child))
183-
else:
184-
data[child.tag].append(child.text)
185-
for key, value in data.items():
186-
if len(value) == 1:
187-
data[key] = value[0]
188-
return data
189-
190-
191190
def ascii_encode_dict(data):
192191
ascii_encode = (
193192
lambda x: x.encode("ascii")

0 commit comments

Comments
 (0)