-
Notifications
You must be signed in to change notification settings - Fork 7
/
declxml.py
1625 lines (1333 loc) · 51.2 KB
/
declxml.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
declxml is a library for declaratively processing XML documents.
Processors
---------------
The declxml library uses processors to define the structure of XML documents. Processors can be
divided into two categories: *primitive processors* and *aggregate processors*.
Primitive Processors
----------------------
Primitive processors are used to parse and serialize simple, primitive values. The following module
functions are used to construct primitive processors:
.. autofunction:: declxml.boolean
.. autofunction:: declxml.floating_point
.. autofunction:: declxml.integer
.. autofunction:: declxml.string
Aggregate Processors
---------------------
Aggregate processors are composed of other processors. These processors are used for values such as
dictionaries, arrays, and user objects.
.. autofunction:: declxml.array
.. autofunction:: declxml.dictionary
.. autofunction:: declxml.named_tuple
.. autofunction:: declxml.user_object
Hooks
------------------
.. autoclass:: declxml.Hooks
.. autoclass:: declxml.ProcessorStateView
:members:
Parsing
----------
.. autofunction:: declxml.parse_from_file
.. autofunction:: declxml.parse_from_string
Serialization
---------------
.. autofunction:: declxml.serialize_to_file
.. autofunction:: declxml.serialize_to_string
Exceptions
------------
.. autoexception:: declxml.XmlError
.. autoexception:: declxml.InvalidPrimitiveValue
.. autoexception:: declxml.InvalidRootProcessor
.. autoexception:: declxml.MissingValue
"""
from io import open
import sys
from typing import ( # noqa pylint: disable=unused-import
Any,
Callable,
Dict,
Iterable,
List,
NamedTuple,
NoReturn,
Optional,
Text,
Tuple,
Type,
Union,
)
import warnings
from xml.dom import minidom # type: ignore
import xml.etree.ElementTree as ET
_PY2 = sys.version_info[0] == 2
class XmlError(Exception):
"""Base error class representing errors processing XML data."""
class InvalidPrimitiveValue(XmlError):
"""Represents errors due to invalid primitive values."""
class InvalidRootProcessor(XmlError):
"""Represents errors due to invalid root processors."""
class MissingValue(XmlError):
"""Represents errors due to missing required values."""
ProcessorLocation = NamedTuple('ProcessorLocation', [
('element_path', Text), # Path to the element relative to the previous location.
('array_index', Optional[int]), # Index of the element if in an array, None if not in an array.
])
class ProcessorStateView(object):
"""Provides an immutable view of the processor state."""
def __init__(
self,
processor_state # type: _ProcessorState
):
# type: (...) -> None
"""
Create a new processor state view.
:param processor_state: Underlying processor state object.
"""
self._processor_state = processor_state
@property
def locations(self):
# type: () -> Iterable[ProcessorLocation]
"""
Get iterator of the ProcessorLocations visited by the processor.
Represents the current location of the processor in the XML document.
A ProcessorLocation represents a single location of a processor in an
XML document. It is a namedtuple with two fields: element_path and
array_index. The element_path field contains the path to the element
in the XML document relative to the previous location in the list of
locations. The array_index field contains the index of the element if
it is in an array, otherwise it is None if the element is not in an
array.
:return: Iterator of ProcessorLocation objects.
"""
return self._processor_state.locations
def raise_error(
self,
exception_type, # type: Type[Exception]
message='' # type: Text
):
# type: (...) -> None
"""
Raise an error with the processor state included in the error message.
:param exception_type: Type of exception to raise
:param message: Error message
"""
self._processor_state.raise_error(exception_type, message)
def __repr__(self):
return repr(self._processor_state)
HookFunction = Callable[[ProcessorStateView, Any], Any]
class Hooks(object):
"""
Contains functions to be invoked during parsing and serialization.
A Hooks object contains two functions: after_parse and before_serialize. Both of these
functions receive two arguments and should return one value.
As their first argument, both functions will receive a ProcessorStateView object representing
the current state of the processor when the function is invoked.
The after_parse function will receive as its second argument the value parsed by the processor
from the XML data during parsing. This function must return a value that will be used by the
processor as its parse result.
Similarly, the before_serialize function will receive as its second argument the value to be
serialized to XML by the processor during serialization. This function must return a value
that the processor will serialize to XML.
Both the after_parse and before_serialize functions are optional.
"""
def __init__(
self,
after_parse=None, # type: Optional[HookFunction]
before_serialize=None # type: Optional[HookFunction]
):
# type: (...) -> None
"""
Create a new Hooks object.
:param after_parse: Function to be invoked after a value has been parsed.
:param before_serialize: Function to be invoked before a value is serialized.
"""
self.after_parse = after_parse
self.before_serialize = before_serialize
class Processor(object): # pragma: no cover
"""Abstract protocol for processors."""
@property
def alias(self):
# type: (...) -> Text
"""Get processor's alias."""
pass
@property
def element_path(self):
# type: (...) -> Text
"""Get path to processor's element."""
pass
@property
def required(self):
# type: (...) -> bool
"""Get whether the processor's value is required."""
pass
def parse_at_element(
self,
element, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse value at element."""
pass
def parse_from_parent(
self,
parent, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse value from parent element."""
pass
def serialize(
self,
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> ET.Element
"""Serialize a value to an XML element."""
pass
def serialize_on_parent(
self,
parent, # type: ET.Element
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> None
"""Serialize value on parent element."""
pass
class RootProcessor(Processor): # pragma: no cover
"""Abstract protocol for root processors."""
def parse_at_root(
self,
root, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse value from root element."""
pass
def parse_from_file(
root_processor, # type: RootProcessor
xml_file_path, # type: Text
encoding='utf-8' # type: Text
):
# type: (...) -> Any
"""
Parse the XML file using the processor starting from the root of the document.
:param root_processor: Root processor of the XML document.
:param xml_file_path: Path to XML file to parse.
:param encoding: Encoding of the file.
:return: Parsed value.
"""
with open(xml_file_path, 'r', encoding=encoding) as xml_file:
xml_string = xml_file.read()
parsed_value = parse_from_string(root_processor, xml_string)
return parsed_value
def parse_from_string(
root_processor, # type: RootProcessor
xml_string # type: Text
):
# type: (...) -> Any
"""
Parse the XML string using the processor starting from the root of the document.
:param xml_string: XML string to parse.
See also :func:`declxml.parse_from_file`
"""
if not _is_valid_root_processor(root_processor):
raise InvalidRootProcessor('Invalid root processor')
parseable_xml_string = xml_string # type: Union[Text, bytes]
if _PY2 and isinstance(xml_string, Text):
parseable_xml_string = xml_string.encode('utf-8')
root = ET.fromstring(parseable_xml_string)
_xml_namespace_strip(root)
state = _ProcessorState()
state.push_location(root_processor.element_path)
return root_processor.parse_at_root(root, state)
def serialize_to_file(
root_processor, # type: RootProcessor
value, # type: Any
xml_file_path, # type: Text
encoding='utf-8', # type: Text
indent=None # type: Optional[Text]
):
# type: (...) -> None
"""
Serialize the value to an XML file using the root processor.
:param root_processor: Root processor of the XML document.
:param value: Value to serialize.
:param xml_file_path: Path to the XML file to which the serialized value will be written.
:param encoding: Encoding of the file.
:param indent: If specified, then the XML will be formatted with the specified indentation.
"""
serialized_value = serialize_to_string(root_processor, value, indent)
with open(xml_file_path, 'w', encoding=encoding) as xml_file:
xml_file.write(serialized_value)
def serialize_to_string(
root_processor, # type: RootProcessor
value, # type: Any
indent=None # type: Optional[Text]
):
# type: (...) -> Text
"""
Serialize the value to an XML string using the root processor.
:return: The serialized XML string.
See also :func:`declxml.serialize_to_file`
"""
if not _is_valid_root_processor(root_processor):
raise InvalidRootProcessor('Invalid root processor')
state = _ProcessorState()
state.push_location(root_processor.element_path)
root = root_processor.serialize(value, state)
state.pop_location()
# Always encode to UTF-8 because element tree does not support other
# encodings in earlier Python versions. See: https://bugs.python.org/issue1767933
serialized_value = ET.tostring(root, encoding='utf-8')
# Since element tree does not support pretty printing XML, we use minidom to do the pretty
# printing
if indent:
serialized_value = minidom.parseString(serialized_value).toprettyxml(
indent=indent, encoding='utf-8'
)
return serialized_value.decode('utf-8')
def array(
item_processor, # type: Processor
alias=None, # type: Optional[Text]
nested=None, # type: Optional[Text]
omit_empty=False, # type: bool
hooks=None # type: Optional[Hooks]
):
# type: (...) -> RootProcessor
"""
Create an array processor that can be used to parse and serialize array data.
XML arrays may be nested within an array element, or they may be embedded
within their parent. A nested array would look like:
.. sourcecode:: xml
<root-element>
<some-element>ABC</some-element>
<nested-array>
<array-item>0</array-item>
<array-item>1</array-item>
</nested-array>
</root-element>
The corresponding embedded array would look like:
.. sourcecode:: xml
<root-element>
<some-element>ABC</some-element>
<array-item>0</array-item>
<array-item>1</array-item>
</root-element>
An array is considered required when its item processor is configured as being
required.
:param item_processor: A declxml processor object for the items of the array.
:param alias: If specified, the name given to the array when read from XML.
If not specified, then the name of the item processor is used instead.
:param nested: If the array is a nested array, then this should be the name of
the element under which all array items are located. If not specified, then
the array is treated as an embedded array. Can also be specified using supported
XPath syntax.
:param omit_empty: If True, then nested arrays will be omitted when serializing if
they are empty. Only valid when nested is specified. Note that an empty array
may only be omitted if it is not itself contained within an array. That is,
for an array of arrays, any empty arrays in the outer array will always be
serialized to prevent information about the original array from being lost
when serializing.
:param hooks: A Hooks object.
:return: A declxml processor object.
"""
processor = _Array(item_processor, alias, nested, omit_empty)
return _processor_wrap_if_hooks(processor, hooks)
def boolean(
element_name, # type: Text
attribute=None, # type: Optional[Text]
required=True, # type: bool
alias=None, # type: Optional[Text]
default=False, # type: Optional[bool]
omit_empty=False, # type: bool
hooks=None # type: Optional[Hooks]
):
# type: (...) -> Processor
"""
Create a processor for boolean values.
:param element_name: Name of the XML element containing the value. Can also be specified
using supported XPath syntax.
:param attribute: If specified, then the value is searched for under the
attribute within the element specified by element_name. If not specified,
then the value is searched for as the contents of the element specified by
element_name.
:param required: Indicates whether the value is required when parsing and serializing.
:param alias: If specified, then this is used as the name of the value when read from
XML. If not specified, then the element_name is used as the name of the value.
:param default: Default value to use if the element is not present. This option is only
valid if required is specified as False.
:param omit_empty: If True, then Falsey values will be omitted when serializing to XML. Note
that Falsey values are never omitted when they are elements of an array. Falsey values can
be omitted only when they are standalone elements.
:param hooks: A Hooks object.
:return: A declxml processor object.
"""
return _PrimitiveValue(
element_name,
_parse_boolean,
attribute,
required,
alias,
default,
omit_empty,
hooks
)
def dictionary(
element_name, # type: Text
children, # type: List[Processor]
required=True, # type: bool
alias=None, # type: Optional[Text]
hooks=None # type: Optional[Hooks]
):
# type: (...) -> RootProcessor
"""
Create a processor for dictionary values.
:param element_name: Name of the XML element containing the dictionary value. Can also be
specified using supported XPath syntax.
:param children: List of declxml processor objects for processing the children
contained within the dictionary.
:param required: Indicates whether the value is required when parsing and serializing.
:param alias: If specified, then this is used as the name of the value when read from
XML. If not specified, then the element_name is used as the name of the value.
:param hooks: A Hooks object.
:return: A declxml processor object.
"""
processor = _Dictionary(element_name, children, required, alias)
return _processor_wrap_if_hooks(processor, hooks)
def floating_point(
element_name, # type: Text
attribute=None, # type: Optional[Text]
required=True, # type: bool
alias=None, # type: Optional[Text]
default=0.0, # type: Optional[float]
omit_empty=False, # type: bool
hooks=None # type: Optional[Hooks]
):
# type: (...) -> Processor
"""
Create a processor for floating point values.
See also :func:`declxml.boolean`
"""
value_parser = _number_parser(float)
return _PrimitiveValue(
element_name,
value_parser,
attribute,
required,
alias,
default,
omit_empty,
hooks
)
def integer(
element_name, # type: Text
attribute=None, # type: Optional[Text]
required=True, # type: bool
alias=None, # type: Optional[Text]
default=0, # type: Optional[int]
omit_empty=False, # type: bool
hooks=None # type: Optional[Hooks]
):
# type: (...) -> Processor
"""
Create a processor for integer values.
See also :func:`declxml.boolean`
"""
value_parser = _number_parser(int)
return _PrimitiveValue(
element_name,
value_parser,
attribute,
required,
alias,
default,
omit_empty,
hooks
)
def named_tuple(
element_name, # type: Text
tuple_type, # type: Type[Tuple]
child_processors, # type: List[Processor]
required=True, # type: bool
alias=None, # type: Optional[Text]
hooks=None # type: Optional[Hooks]
):
# type: (...) -> RootProcessor
"""
Create a processor for namedtuple values.
:param tuple_type: The namedtuple type.
See also :func:`declxml.dictionary`
"""
converter = _named_tuple_converter(tuple_type)
processor = _Aggregate(element_name, converter, child_processors, required, alias)
return _processor_wrap_if_hooks(processor, hooks)
def string(
element_name, # type: Text
attribute=None, # type: Optional[Text]
required=True, # type: bool
alias=None, # type: Optional[Text]
default='', # type: Optional[Text]
omit_empty=False, # type: bool
strip_whitespace=True, # type: bool
hooks=None # type: Optional[Hooks]
):
# type: (...) -> Processor
"""
Create a processor for string values.
:param strip_whitespace: Indicates whether leading and trailing whitespace should be stripped
from parsed string values.
See also :func:`declxml.boolean`
"""
value_parser = _string_parser(strip_whitespace)
return _PrimitiveValue(
element_name,
value_parser,
attribute,
required,
alias,
default,
omit_empty,
hooks
)
def user_object(
element_name, # type: Text
cls, # type: Type[Any]
child_processors, # type: List[Processor]
required=True, # type: bool
alias=None, # type: Optional[Text]
hooks=None # type: Optional[Hooks]
):
# type: (...) -> RootProcessor
"""
Create a processor for user objects.
:param cls: Class object with a no-argument constructor or other callable no-argument object.
See also :func:`declxml.dictionary`
"""
converter = _user_object_converter(cls)
processor = _Aggregate(element_name, converter, child_processors, required, alias)
return _processor_wrap_if_hooks(processor, hooks)
# Defines pair of functions to convert between aggregates and dictionaries
_AggregateConverter = NamedTuple('_AggregateConverter', [
('from_dict', Callable[[Dict], Any]),
('to_dict', Callable[[Any], Dict]),
])
class _Aggregate(RootProcessor):
"""An XML processor for processing aggregates."""
def __init__(
self,
element_path, # type: Text
converter, # type: _AggregateConverter
child_processors, # type: List[Processor]
required=True, # type: bool
alias=None # type: Optional[Text]
):
# type: (...) -> None
self._element_path = element_path
self._converter = converter
self._required = required
self._dictionary = _Dictionary(element_path, child_processors, required, alias)
if alias:
self._alias = alias
else:
self._alias = element_path
@property
def alias(self):
# type: (...) -> Text
"""Get processor's alias."""
return self._alias
@property
def element_path(self):
# type: (...) -> Text
"""Get path to processor's element."""
return self._element_path
@property
def required(self):
# type: (...) -> bool
"""Get whether the processor's value is required."""
return self._required
def parse_at_element(
self,
element, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the provided element as an aggregate."""
parsed_dict = self._dictionary.parse_at_element(element, state)
return self._converter.from_dict(parsed_dict)
def parse_at_root(
self,
root, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the root XML element as an aggregate."""
parsed_dict = self._dictionary.parse_at_root(root, state)
return self._converter.from_dict(parsed_dict)
def parse_from_parent(
self,
parent, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the aggregate from the provided parent XML element."""
parsed_dict = self._dictionary.parse_from_parent(parent, state)
return self._converter.from_dict(parsed_dict)
def serialize(
self,
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> ET.Element
"""Serialize the value to a new element and returns the element."""
dict_value = self._converter.to_dict(value)
return self._dictionary.serialize(dict_value, state)
def serialize_on_parent(
self,
parent, # type: ET.Element
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> None
"""Serialize the value and adds it to the parent."""
dict_value = self._converter.to_dict(value)
self._dictionary.serialize_on_parent(parent, dict_value, state)
class _Array(RootProcessor):
"""An XML processor for Array values."""
def __init__(
self,
item_processor, # type: Processor
alias=None, # type: Optional[Text]
nested=None, # type: Optional[Text]
omit_empty=False # type: bool
):
# type: (...) -> None
self._item_processor = item_processor
self._nested = nested
self._required = item_processor.required
if alias:
self._alias = alias
elif nested:
self._alias = nested
else:
self._alias = item_processor.alias
if self._nested:
self._element_path = self._nested
else:
self._element_path = '.' # Array is embedded directly on parent
self._item_path = self.element_path + '/' + self._item_processor.element_path
if not nested or self.required:
self.omit_empty = False
if omit_empty:
warnings.warn('omit_empty ignored for non-nested and/or required arrays')
else:
self.omit_empty = omit_empty
@property
def alias(self):
# type: (...) -> Text
"""Get processor's alias."""
return self._alias
@property
def element_path(self):
# type: (...) -> Text
"""Get path to processor's element."""
return self._element_path
@property
def required(self):
# type: (...) -> bool
"""Get whether the processor's value is required."""
return self._required
def parse_at_element(
self,
element, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the provided element as an array."""
item_iter = element.findall(self._item_processor.element_path)
return self._parse(item_iter, state)
def parse_at_root(
self,
root, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the root XML element as an array."""
if not self._nested:
raise InvalidRootProcessor('Non-nested array "{}" cannot be root element'.format(
self.alias))
parsed_array = [] # type: List
array_element = _element_find_from_root(root, self._nested)
if array_element is not None:
parsed_array = self.parse_at_element(array_element, state)
elif self.required:
raise MissingValue('Missing required array at root: "{}"'.format(self._nested))
return parsed_array
def parse_from_parent(
self,
parent, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the array data from the provided parent XML element."""
item_iter = parent.findall(self._item_path)
return self._parse(item_iter, state)
def serialize(
self,
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> ET.Element
"""Serialize the value into a new Element object and return it."""
if self._nested is None:
state.raise_error(InvalidRootProcessor,
'Cannot directly serialize a non-nested array "{}"'
.format(self.alias))
if not value and self.required:
state.raise_error(MissingValue, 'Missing required array: "{}"'.format(
self.alias))
start_element, end_element = _element_path_create_new(self._nested)
self._serialize(end_element, value, state)
return start_element
def serialize_on_parent(
self,
parent, # type: ET.Element
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> None
"""Serialize the value and append it to the parent element."""
if not value and self.required:
state.raise_error(MissingValue, 'Missing required array: "{}"'.format(
self.alias))
if not value and self.omit_empty:
return # Do nothing
if self._nested is not None:
array_parent = _element_get_or_add_from_parent(parent, self._nested)
else:
# Embedded array has all items serialized directly on the parent.
array_parent = parent
self._serialize(array_parent, value, state)
def _parse(
self,
item_iter, # type: Iterable[ET.Element]
state # type: _ProcessorState
):
# type: (...) -> List
"""Parse the array data using the provided iterator of XML elements."""
parsed_array = []
for i, item in enumerate(item_iter):
state.push_location(self._item_processor.element_path, i)
parsed_array.append(self._item_processor.parse_at_element(item, state))
state.pop_location()
if not parsed_array and self.required:
state.raise_error(MissingValue, 'Missing required array "{}"'.format(self.alias))
return parsed_array
def _serialize(
self,
array_parent, # type: ET.Element
value, # type: List
state # type: _ProcessorState
):
# type: (...) -> None
"""Serialize the array value and add it to the array parent element."""
if not value:
# Nothing to do. Avoid attempting to iterate over a possibly
# None value.
return
for i, item_value in enumerate(value):
state.push_location(self._item_processor.element_path, i)
item_element = self._item_processor.serialize(item_value, state)
array_parent.append(item_element)
state.pop_location()
class _Dictionary(RootProcessor):
"""An XML processor for dictionary values."""
def __init__(
self,
element_path, # type: Text
child_processors, # type: List[Processor]
required=True, # type: bool
alias=None # type: Optional[Text]
):
# type: (...) -> None
self._element_path = element_path
self._child_processors = child_processors
self._required = required
if alias:
self._alias = alias
else:
self._alias = element_path
@property
def alias(self):
# type: (...) -> Text
"""Get processor's alias."""
return self._alias
@property
def element_path(self):
# type: (...) -> Text
"""Get path to processor's element."""
return self._element_path
@property
def required(self):
# type: (...) -> bool
"""Get whether the processor's value is required."""
return self._required
def parse_at_element(
self,
element, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the provided element as a dictionary."""
parsed_dict = {}
for child in self._child_processors:
state.push_location(child.element_path)
parsed_dict[child.alias] = child.parse_from_parent(element, state)
state.pop_location()
return parsed_dict
def parse_at_root(
self,
root, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the root XML element as a dictionary."""
parsed_dict = {} # type: Dict
dict_element = _element_find_from_root(root, self.element_path)
if dict_element is not None:
parsed_dict = self.parse_at_element(dict_element, state)
elif self.required:
raise MissingValue('Missing required root aggregate "{}"'.format(self.element_path))
return parsed_dict
def parse_from_parent(
self,
parent, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the dictionary data from the provided parent XML element."""
element = parent.find(self.element_path)
if element is None and self.required:
state.raise_error(
MissingValue, 'Missing required aggregate "{}"'.format(self.element_path)
)
elif element is not None:
return self.parse_at_element(element, state)
return {}
def serialize(
self,
value, # type: Any
state # type: _ProcessorState
):