-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathxml_helper.py
376 lines (307 loc) · 12.7 KB
/
xml_helper.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# -*- coding: utf-8 -*-
"""
testerxml
This file was automatically generated by APIMATIC v3.0 (
https://www.apimatic.io ).
"""
import xml.etree.ElementTree as ET
import datetime
import dateutil.parser
from apimatic_core.utilities.api_helper import ApiHelper
class XmlHelper:
"""This class hold utility methods for xml serialization and
deserialization.
"""
@staticmethod
def serialize_to_xml(value, root_element_name):
"""Serializes a given value to an xml document.
Args:
value (mixed): The value to serialize.
root_element_name (str): The name of the document's root element.
"""
root = ET.Element(root_element_name)
if value is not None:
XmlHelper.add_to_element(root, value)
return ET.tostring(root).decode()
@staticmethod
def serialize_list_to_xml(value, root_element_name, array_item_name):
"""Serializes a given list of values to an xml document.
Args:
value (mixed): The value to serialize.
root_element_name (str): The name of the document's root element.
array_item_name (str): The element name to use for each item in
'values'.
"""
root = ET.Element(root_element_name)
XmlHelper.add_list_as_subelement(root, value, array_item_name)
return ET.tostring(root).decode()
@staticmethod
def serialize_dict_to_xml(value, root_element_name):
"""Serializes a given dict of values to an xml document.
Args:
value (mixed): The dict to serialize.
root_element_name (str): The name of the document's root element.
"""
root = ET.Element(root_element_name)
XmlHelper.add_dict_as_subelement(root, value)
return ET.tostring(root).decode()
@staticmethod
def add_to_element(element, value):
"""Converts the given value to xml and adds it to an
existing xml.etree.Element.
Args:
element (xml.etree.Element): The xml tag to add the 'value' to.
value (mixed): The value to add to the element.
"""
# These classes can be cast directly.
if isinstance(value, bool):
element.text = str(value).lower()
elif isinstance(value, (int, float, str, datetime.date,
ApiHelper.CustomDate)):
element.text = str(value)
else:
value.to_xml_sub_element(element)
@staticmethod
def add_as_attribute(root, value, name):
"""Sets an attribute on an xml.etree.Element instance if the value
isn't None.
Args:
root (xml.etree.Element): The parent of this xml attribute.
value (mixed): The value to set to the attribute.
name (str): The name of attribute being set.
"""
if value is not None:
if isinstance(value, bool):
root.set(name, str(value).lower())
else:
root.set(name, str(value))
@staticmethod
def add_as_subelement(root, value, name):
"""Converts the given value to an xml.etree.Element if it is not None
and adds it to an existing xml.etree.Element.
Args:
root (xml.etree.Element): The parent of this xml element.
value (mixed): The value to add to the element.
name (str): The name of the element being added.
"""
if value is not None:
tag = ET.SubElement(root, name)
XmlHelper.add_to_element(tag, value)
@staticmethod
def add_list_as_subelement(root, items, item_name,
wrapping_element_name=None):
"""Converts the given list to an xml.etree.Element if it is not None
and adds it to an existing xml.etree.Element.
Args:
root (xml.etree.Element): The parent of this xml element.
items (list): The list of values to add to the element.
item_name (str): The element name to use for each item in 'items'.
wrapping_element_name (str): The element name to use for the
wrapping element, if needed.
"""
if items is not None:
if wrapping_element_name is not None:
parent = ET.SubElement(root, wrapping_element_name)
else:
parent = root
for item in items:
sub_elem = ET.SubElement(parent, item_name)
XmlHelper.add_to_element(sub_elem, item)
@staticmethod
def add_dict_as_subelement(root, items, dictionary_name=None):
"""Converts the given dict to an xml.etree.Element if it is not None
and adds it to an existing xml.etree.Element.
Args:
root (xml.etree.Element): The parent of this xml element.
items (dict): The dict of values to add to the element.
dictionary_name (str): The element name to use for the
encapsulating element.
"""
if items is not None:
if dictionary_name is not None:
parent = ET.SubElement(root, dictionary_name)
else:
parent = root
for key, value in items.items():
if isinstance(value, list):
XmlHelper.add_list_as_subelement(parent, value, key)
else:
XmlHelper.add_as_subelement(parent, value, key)
@staticmethod
def deserialize_xml(xml, clazz):
"""Deserializes an xml document to a python object of the type given
by 'clazz'.
Args:
xml (str): An xml document to deserialize.
clazz (class): The class that the deserialized object should
belong to.
"""
if not xml:
return None
root = ET.fromstring(xml)
return XmlHelper.value_from_xml_element(root, clazz)
@staticmethod
def deserialize_xml_to_list(xml, item_name, clazz):
"""Deserializes an xml document to a list of python objects, each of
the type given by 'clazz'.
Args:
xml (str): An xml document to deserialize.
item_name (str): The name of the elements that need to be extracted
into a list.
clazz (class): The class that the deserialized object should
belong to.
"""
if not xml:
return None
root = ET.fromstring(xml)
return XmlHelper.list_from_xml_element(root, item_name, clazz)
@staticmethod
def deserialize_xml_to_dict(xml, clazz):
"""Deserializes an xml document to a dictionary of python objects, each of
the type given by 'clazz'.
Args:
xml (str): An xml document to deserialize.
clazz (class): The class that the values of the dictionary should
belong to.
"""
if not xml:
return None
root = ET.fromstring(xml)
return XmlHelper.dict_from_xml_element(root, clazz)
@staticmethod
def value_from_xml_attribute(attribute, clazz):
"""Extracts the value from an attribute and converts it to the type
given by 'clazz'.
Args:
clazz (class): The class that the deserialized object should
belong to.
"""
if attribute is None:
return None
conversion_function = XmlHelper.converter(clazz)
return conversion_function(attribute) if conversion_function is not None else None
@staticmethod
def value_from_xml_element(element, clazz):
"""Extracts the value from an element and converts it to the type given
by 'clazz'.
Args:
clazz (class): The class that the deserialized object should
belong to.
"""
if element is None:
return None
# These classes can be cast directly.
if clazz in [int, float, str, bool, datetime.date] or\
issubclass(clazz, ApiHelper.CustomDate):
conversion_function = XmlHelper.converter(clazz)
value = element.text
else:
conversion_function = clazz.from_element
value = element
return conversion_function(value)
@staticmethod
def list_from_xml_element(root, item_name, clazz, wrapping_element_name=None):
"""Deserializes an xml document to a list of python objects, each of
the type given by 'clazz'.
Args:
root (str): An xml document to deserialize.
item_name (str): The name of the elements that need to be extracted
into a list.
clazz (class): The class that the deserialized object should
belong to.
wrapping_element_name (str): The name of the wrapping element for
the xml element array.
"""
if root is None:
return None
elements = XmlHelper.get_elements(root, wrapping_element_name, item_name)
if elements is None:
return None
return [XmlHelper.value_from_xml_element(element, clazz) for
element in elements]
@staticmethod
def dict_from_xml_element(element, clazz):
"""Extracts the values from an element and converts them to a
dictionary with values of type 'clazz'.
Args:
clazz (class): The class that the entries of the dictionary should
belong to.
"""
if element is None:
return None
entries = list(element)
conversion_function = XmlHelper.converter(clazz)
return {entry.tag: conversion_function(entry.text) for
entry in entries}
@staticmethod
def converter(clazz):
"""Provides the function to use for converting a string to the type
given by 'clazz'.
Args:
clazz (class): The class to find the conversion function for.
"""
# These classes can be cast directly.
if clazz in [int, float, str]:
def conversion_function(value):
return clazz(value)
elif clazz is bool:
def conversion_function(value):
return value.lower() == 'true'
elif clazz is datetime.date:
def conversion_function(value):
return dateutil.parser.parse(value).date()
# DateTime classes have their own method to convert from string.
elif issubclass(clazz, ApiHelper.CustomDate):
def conversion_function(value):
return clazz.from_value(value)
return conversion_function
@staticmethod
def value_from_one_of_xml_elements(root, mapping_data):
"""Extracts the value from an element and converts it to the type given
by 'clazz'.
Args:
mapping_data (dict): A dictionary mapping possible element names
for a given field to corresponding types.
"""
if not mapping_data:
return None
for element_name, tup in mapping_data.items():
clazz = tup[0]
is_array = tup[1]
wrapping_element_name = tup[2]
if is_array:
elements = XmlHelper.get_elements(root, wrapping_element_name, element_name)
if elements is not None and len(elements) > 0:
return XmlHelper.list_from_xml_element(
root, element_name, clazz, wrapping_element_name)
else:
element = root.find(element_name)
if element is not None:
return XmlHelper.value_from_xml_element(element, clazz)
@staticmethod
def list_from_multiple_one_of_xml_element(root, mapping_data):
"""Deserializes an xml document to a list of python objects
where all types of oneof schemas are allowed (when the outer
model is an array)
Args:
root (str): An xml document to deserialize.
mapping_data (dict): A dictionary mapping possible element names
for a given field to corresponding types.
"""
arr = []
for elem in root.iter():
if elem.tag in mapping_data:
arr.append(XmlHelper.value_from_xml_element(
elem, mapping_data[elem.tag][0]))
if len(arr) > 0:
return arr
else:
return None
@staticmethod
def get_elements(root, wrapping_element_name, item_name):
if wrapping_element_name is None:
return root.findall(item_name)
elif root.find(wrapping_element_name) is None:
return None
else:
return root.find(wrapping_element_name).findall(item_name)