7
7
import os
8
8
import math
9
9
import numpy as np
10
+ import xmltodict
10
11
11
12
from modelspec .base_types import print_
12
13
from modelspec .base_types import EvaluableExpression
@@ -72,7 +73,7 @@ def load_xml(filename: str):
72
73
# Convert the ElementTree object to a dictionary
73
74
data = element_to_dict (root )
74
75
75
- return data
76
+ return convert_values ( data )
76
77
77
78
78
79
def element_to_dict (element ):
@@ -100,6 +101,28 @@ def element_to_dict(element):
100
101
101
102
return result
102
103
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
+
103
126
104
127
def save_to_json_file (info_dict , filename , indent = 4 ):
105
128
@@ -118,7 +141,7 @@ def save_to_yaml_file(info_dict, filename, indent=4):
118
141
fp .write (stry )
119
142
120
143
121
- def save_to_xml_file (info_dict , filename , indent = 4 ):
144
+ def save_to_xml_file (info_dict , filename , indent = 4 , root = "modelspec" ):
122
145
"""
123
146
Save a dictionary to an XML file.
124
147
@@ -128,7 +151,7 @@ def save_to_xml_file(info_dict, filename, indent=4):
128
151
indent (int, optional): The number of spaces used for indentation in the XML file.
129
152
Defaults to 4.
130
153
"""
131
- root = ET .Element (" root" )
154
+ root = ET .Element (root )
132
155
133
156
build_xml_element (root , info_dict )
134
157
@@ -164,30 +187,6 @@ def build_xml_element(parent, data):
164
187
parent .text = str (data )
165
188
166
189
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
-
191
190
def ascii_encode_dict (data ):
192
191
ascii_encode = (
193
192
lambda x : x .encode ("ascii" )
0 commit comments