/
generateDS.py
executable file
·7473 lines (7013 loc) · 296 KB
/
generateDS.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
#!/usr/bin/env python
"""
Synopsis:
Generate Python classes from XML schema definition.
Input is read from in_xsd_file or, if "-" (dash) arg, from stdin.
Output is written to files named in "-o" and "-s" options.
Usage:
python generateDS.py [ options ] <xsd_file>
python generateDS.py [ options ] -
Options:
-h, --help Display this help information.
-o <outfilename> Output file name for data representation classes
-s <subclassfilename> Output file name for subclasses
-p <prefix> Prefix string to be pre-pended to the class names
-f Force creation of output files. Do not ask.
-a <namespaceabbrev> Namespace abbreviation, e.g. "xsd:".
Default = 'xs:'.
-b <behaviorfilename> Input file name for behaviors added to subclasses
-m Generate properties for member variables
-c <xmlcatalogfilename> Input file name to load an XML catalog
--one-file-per-xsd Create a python module for each XSD processed.
--output-directory="XXX" Used in conjunction with --one-file-per-xsd.
The directory where the modules will be created.
--module-suffix="XXX" To be used in conjunction with --one-file-per-xsd.
Append XXX to the end of each file created.
--subclass-suffix="XXX" Append XXX to the generated subclass names.
Default="Sub".
--root-element="XX" When parsing, assume XX is root element of
--root-element="XX|YY" instance docs. Default is first element defined
in schema. If YY is added, then YY is used as the
top level class; if YY omitted XX is the default.
class. Also see section "Recognizing the top level
element" in the documentation.
--super="XXX" Super module name in generated subclass
module. Default="???"
--validator-bodies=path Path to a directory containing files that provide
bodies (implementations) of validator methods.
--use-old-simpletype-validators
Use the old style simpleType validator functions
stored in a specified directory, instead of the
new style validators generated directly from the
XML schema. See option --validator-bodies.
--use-getter-setter Generate getter and setter methods. Values:
"old" - Name getters/setters getVar()/setVar().
"new" - Name getters/setters get_var()/set_var().
"none" - Do not generate getter/setter methods.
Default is "new".
--use-source-file-as-module-name
Used in conjunction with --one-file-per-xsd to
use the source XSD file names to determine the
module name of the generated classes.
--user-methods= <module>,
-u <module> Optional module containing user methods. See
section "User Methods" in the documentation.
--no-dates Do not include the current date in the generated
files. This is useful if you want to minimize
the amount of (no-operation) changes to the
generated python code.
--no-versions Do not include the current version in the
generated files. This is useful if you want
to minimize the amount of (no-operation)
changes to the generated python code.
--no-process-includes Do not use process_includes.py to pre-process
included XML schema files. By default,
generateDS.py will insert content from files
referenced by xs:include and xs:import elements
into the XML schema to be processed and perform
several other pre-procesing tasks. You likely do
not want to use this option; its use has been
reported to result in errors in generated modules.
Consider using --no-collect-includes and/or
--no-redefine-groups instead.
--no-collect-includes Do not (recursively) collect and insert schemas
referenced by xs:include and xs:import elements.
--no-redefine-groups Do not pre-process and redefine group definitions.
--silence Normally, the code generated with generateDS
echoes the information being parsed. To prevent
the echo from occurring, use the --silence switch.
Also note optional "silence" parameter on
generated functions, e.g. parse, parseString, etc.
--namespacedef='xmlns:abc="http://www.abc.com"'
Namespace definition to be passed in as the
value for the namespacedef_ parameter of
the export() method by the generated
parse() and parseString() functions.
Default=''.
--no-namespace-defs Do not pass namespace definitions as the value
for the namespacedef_ parameter of the export
method, even if it can be extraced from the
schema.
--external-encoding=<encoding>
Encode output written by the generated export
methods using this encoding. Default, if omitted,
is the value returned by sys.getdefaultencoding().
Example: --external-encoding='utf-8'.
--member-specs=list|dict
Generate member (type) specifications in each
class: a dictionary of instances of class
MemberSpec_ containing member name, type,
and array or not. Allowed values are
"list" or "dict". Default: do not generate.
--export=<export-list> Specifies export functions to be generated.
Value is a whitespace separated list of
any of the following:
write -- write XML to file
literal -- write out python code
etree -- build element tree (can serialize
to XML)
Example: "write etree"
Default: "write"
--always-export-default Always export elements and attributes that
a default value even when the current value
is equal to the default. Default: False.
--disable-generatedssuper-lookup
Disables the generatetion of the lookup logic for
presence of an external module from which to load
a custom `GeneratedsSuper` base-class definition.
--disable-xml Disables generation of all XML build/export
methods and command line interface
--preserve-cdata-tags Preserve CDATA tags. Default: False
--cleanup-name-list=<replacement-map>
Specifies list of 2-tuples used for cleaning
names. First element is a regular expression
search pattern and second is a replacement.
Example: "[('[-:.]', '_'), ('^__', 'Special')]"
Default: "[('[-:.]', '_')]"
-q, --no-questions Do not ask questions, for example,
force overwrite.
--no-warnings Do not print warning messages.
--session=mysession.session
Load and use options from session file. You can
create session file in generateds_gui.py. Or,
copy and edit sample.session from the
distribution.
--fix-type-names="oldname1:newname1;oldname2:newname2;..."
Fix up (replace) complex type names.
--version Print version and exit.
Usage example:
$ python generateDS.py -f -o sample_lib.py sample_api.xsd
creates (with force over-write) sample_lib.py from sample_api.xsd.
$ python generateDS.py -o sample_lib.py -s sample_app1.py \\
--member-specs=dict sample_api.xsd
creates sample_lib.py superclass and sample_app1.py subclass modules;
also generates member specifications in each class (in a dictionary).
"""
## LICENSE
## Copyright (c) 2003 Dave Kuhlman
## Permission is hereby granted, free of charge, to any person obtaining
## a copy of this software and associated documentation files (the
## "Software"), to deal in the Software without restriction, including
## without limitation the rights to use, copy, modify, merge, publish,
## distribute, sublicense, and/or sell copies of the Software, and to
## permit persons to whom the Software is furnished to do so, subject to
## the following conditions:
## The above copyright notice and this permission notice shall be
## included in all copies or substantial portions of the Software.
## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
## EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
## MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
## IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
## CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
## TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
## SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from __future__ import print_function
from six.moves import input
import six
import sys
import os.path
import time
import getopt
import imp
from xml.sax import handler, make_parser
import logging
import keyword
import textwrap
import hashlib
import operator
import re
if sys.version_info.major == 2:
import urllib2
import StringIO
else:
import urllib.request
import urllib.error
import urllib.parse
import io
from functools import reduce
_log = logging.getLogger(__name__)
## import warnings
## warnings.warn('importing IPShellEmbed', UserWarning)
## from IPython.Shell import IPShellEmbed
## args = ''
## ipshell = IPShellEmbed(args,
## banner = 'Dropping into IPython',
## exit_msg = 'Leaving Interpreter, back to program.')
# Then use the following line where and when you want to drop into the
# IPython shell:
# ipshell('<some message> -- Entering ipshell.\\nHit Ctrl-D to exit')
#
# Global variables etc.
#
#
# Do not modify the following VERSION comments.
# Used by updateversion.py.
##VERSION##
VERSION = '2.29.14'
##VERSION##
BaseStrTypes = six.string_types
GenerateProperties = 0
UseGetterSetter = 'new'
UseOldSimpleTypeValidators = False
UseGeneratedssuperLookup = True
SchemaLxmlTree = None
XsdFileName = []
MemberSpecs = None
DelayedElements = set()
DelayedElements_subclass = set()
AlreadyGenerated = set()
AlreadyGenerated_subclass = set()
PostponedExtensions = []
LoopcheckOneperChecksums = set()
ElementsForSubclasses = []
ElementDict = {}
fqnToElementDict = {}
fqnToModuleNameMap = {}
Force = False
NoQuestions = False
NoDates = False
NoVersion = False
AlwaysExportDefault = False
Dirpath = []
ExternalEncoding = sys.getdefaultencoding()
Namespacedef = ''
NoNameSpaceDefs = False
CleanupNameList = [(re.compile('[-:.]'), '_')]
NamespacesDict = {}
SchemaNamespaceDict = {}
prefixToNamespaceMap = {}
MappingTypes = {}
Targetnamespace = ""
NameTable = {
'type': 'type_',
'float': 'float_',
'build': 'build_',
}
for kw in keyword.kwlist:
NameTable[kw] = '%s_' % kw
SubclassSuffix = 'Sub'
RootElement = None
AttributeGroups = {}
ElementGroups = {}
SubstitutionGroups = {}
#
# SubstitutionGroups can also include simple types that are
# not (defined) elements. Keep a list of these simple types.
# These are simple types defined at top level.
SimpleElementDict = {}
SimpleTypeDict = {}
ValidatorBodiesBasePath = None
UserMethodsPath = None
UserMethodsModule = None
XsdNameSpace = ''
CurrentNamespacePrefix = 'xs:'
AnyTypeIdentifier = '__ANY__'
ExportWrite = True
ExportEtree = False
ExportLiteral = False
XmlDisabled = False
FixTypeNames = None
SingleFileOutput = True
UseSourceFileAsModuleName = False
OutputDirectory = None
ModuleSuffix = ""
PreserveCdataTags = False
NoWarnings = False
SchemaToPythonTypeMap = {}
# Initialize constants.
CurrentNamespacePrefix = None
StringType = None
TokenType = None
IntegerType = None
DecimalType = None
PositiveIntegerType = None
NegativeIntegerType = None
NonPositiveIntegerType = None
NonNegativeIntegerType = None
BooleanType = None
FloatType = None
DoubleType = None
NumericTypes = None
ElementType = None
ComplexTypeType = None
GroupType = None
SequenceType = None
ChoiceType = None
AttributeGroupType = None
AttributeType = None
SchemaType = None
DateTimeType = None
DateType = None
TimeType = None
GYearType = None
GYearMonthType = None
GMonthType = None
GMonthDayType = None
GDayType = None
DateTimeGroupType = None
SimpleContentType = None
ComplexContentType = None
ExtensionType = None
IDType = None
IDREFType = None
IDREFSType = None
IDTypes = None
NameType = None
NCNameType = None
QNameType = None
NameTypes = None
AnyAttributeType = None
SimpleTypeType = None
RestrictionType = None
WhiteSpaceType = None
ListType = None
EnumerationType = None
UnionType = None
AnyType = None
AnnotationType = None
DocumentationType = None
OtherSimpleTypes = None
Base64Type = None
def set_type_constants(nameSpace):
global CurrentNamespacePrefix, \
StringType, TokenType, \
IntegerType, DecimalType, \
PositiveIntegerType, NegativeIntegerType, \
NonPositiveIntegerType, NonNegativeIntegerType, \
BooleanType, FloatType, DoubleType, \
NumericTypes, \
ElementType, ComplexTypeType, GroupType, SequenceType, ChoiceType, \
AttributeGroupType, AttributeType, SchemaType, \
DateTimeType, DateType, TimeType, \
DateTimeGroupType, \
GYearType, GYearMonthType, GMonthType, GMonthDayType, GDayType, \
SimpleContentType, ComplexContentType, ExtensionType, \
IDType, IDREFType, IDREFSType, IDTypes, \
NameType, NCNameType, QNameType, NameTypes, \
AnyAttributeType, SimpleTypeType, RestrictionType, \
WhiteSpaceType, ListType, EnumerationType, UnionType, \
Base64Type, AnyType, \
AnnotationType, DocumentationType, \
OtherSimpleTypes
CurrentNamespacePrefix = nameSpace
AttributeGroupType = nameSpace + 'attributeGroup'
AttributeType = nameSpace + 'attribute'
BooleanType = nameSpace + 'boolean'
ChoiceType = nameSpace + 'choice'
SimpleContentType = nameSpace + 'simpleContent'
ComplexContentType = nameSpace + 'complexContent'
ComplexTypeType = nameSpace + 'complexType'
GroupType = nameSpace + 'group'
SimpleTypeType = nameSpace + 'simpleType'
RestrictionType = nameSpace + 'restriction'
WhiteSpaceType = nameSpace + 'whiteSpace'
AnyAttributeType = nameSpace + 'anyAttribute'
DateTimeType = nameSpace + 'dateTime'
TimeType = nameSpace + 'time'
DateType = nameSpace + 'date'
GYearType = nameSpace + 'gYear'
GYearMonthType = nameSpace + 'gYearMonth'
GMonthType = nameSpace + 'gMonth'
GMonthDayType = nameSpace + 'gMonthDay'
GDayType = nameSpace + 'gDay'
DateTimeGroupType = (
DateTimeType, DateType, TimeType,
GYearType, GYearMonthType, GMonthType, GMonthDayType, GDayType,
)
IntegerType = (
nameSpace + 'integer',
nameSpace + 'unsignedShort',
nameSpace + 'unsignedLong',
nameSpace + 'unsignedInt',
nameSpace + 'unsignedByte',
nameSpace + 'byte',
nameSpace + 'short',
nameSpace + 'long',
nameSpace + 'int',
)
DecimalType = nameSpace + 'decimal'
PositiveIntegerType = nameSpace + 'positiveInteger'
NegativeIntegerType = nameSpace + 'negativeInteger'
NonPositiveIntegerType = nameSpace + 'nonPositiveInteger'
NonNegativeIntegerType = nameSpace + 'nonNegativeInteger'
DoubleType = nameSpace + 'double'
ElementType = nameSpace + 'element'
ExtensionType = nameSpace + 'extension'
FloatType = nameSpace + 'float'
IDREFSType = nameSpace + 'IDREFS'
IDREFType = nameSpace + 'IDREF'
IDType = nameSpace + 'ID'
IDTypes = (IDREFSType, IDREFType, IDType, )
SchemaType = nameSpace + 'schema'
SequenceType = nameSpace + 'sequence'
StringType = (
nameSpace + 'string',
nameSpace + 'duration',
nameSpace + 'anyURI',
nameSpace + 'hexBinary',
nameSpace + 'normalizedString',
nameSpace + 'NMTOKEN',
nameSpace + 'ID',
nameSpace + 'Name',
nameSpace + 'language',
)
NumericTypes = set([
IntegerType,
DecimalType,
PositiveIntegerType,
NegativeIntegerType,
NonPositiveIntegerType,
NonNegativeIntegerType,
FloatType,
DoubleType,
])
NumericTypes.update(set(IntegerType))
Base64Type = nameSpace + 'base64Binary'
TokenType = nameSpace + 'token'
NameType = nameSpace + 'Name'
NCNameType = nameSpace + 'NCName'
QNameType = nameSpace + 'QName'
NameTypes = (NameType, NCNameType, QNameType, )
ListType = nameSpace + 'list'
EnumerationType = nameSpace + 'enumeration'
UnionType = nameSpace + 'union'
AnnotationType = nameSpace + 'annotation'
DocumentationType = nameSpace + 'documentation'
AnyType = nameSpace + 'any'
OtherSimpleTypes = (
nameSpace + 'ENTITIES',
nameSpace + 'ENTITY',
nameSpace + 'ID',
nameSpace + 'IDREF',
nameSpace + 'IDREFS',
nameSpace + 'NCName',
nameSpace + 'NMTOKEN',
nameSpace + 'NMTOKENS',
nameSpace + 'NOTATION',
nameSpace + 'Name',
nameSpace + 'QName',
nameSpace + 'anyURI',
nameSpace + 'base64Binary',
nameSpace + 'hexBinary',
nameSpace + 'boolean',
nameSpace + 'byte',
nameSpace + 'date',
nameSpace + 'dateTime',
nameSpace + 'time',
nameSpace + 'decimal',
nameSpace + 'double',
nameSpace + 'duration',
nameSpace + 'float',
nameSpace + 'gDay',
nameSpace + 'gMonth',
nameSpace + 'gMonthDay',
nameSpace + 'gYear',
nameSpace + 'gYearMonth',
nameSpace + 'int',
nameSpace + 'integer',
nameSpace + 'language',
nameSpace + 'long',
nameSpace + 'negativeInteger',
nameSpace + 'nonNegativeInteger',
nameSpace + 'nonPositiveInteger',
nameSpace + 'normalizedString',
nameSpace + 'positiveInteger',
nameSpace + 'short',
nameSpace + 'string',
nameSpace + 'time',
nameSpace + 'token',
nameSpace + 'unsignedByte',
nameSpace + 'unsignedInt',
nameSpace + 'unsignedLong',
nameSpace + 'unsignedShort',
nameSpace + 'anySimpleType',
)
global SchemaToPythonTypeMap
SchemaToPythonTypeMap = {
BooleanType: 'bool',
DecimalType: 'float',
DoubleType: 'float',
FloatType: 'float',
NegativeIntegerType: 'int',
NonNegativeIntegerType: 'int',
NonPositiveIntegerType: 'int',
PositiveIntegerType: 'int',
}
SchemaToPythonTypeMap.update(dict((x, 'int') for x in IntegerType))
#
# For debugging.
#
# Print only if DEBUG is true.
DEBUG = 0
def dbgprint(level, msg):
if DEBUG and level > 0:
print(msg)
def pplist(lst):
for count, item in enumerate(lst):
print('%d. %s' % (count, item))
#
# Representation of element definition.
#
def showLevel(outfile, level):
for idx in range(level):
outfile.write(' ')
class XschemaElementBase:
def __init__(self):
pass
class SimpleTypeElement(XschemaElementBase):
def __init__(self, name):
XschemaElementBase.__init__(self)
self.name = name
self.base = None
self.collapseWhiteSpace = 0
# Attribute definitions for the current attributeGroup, if
# there is one.
self.attributeGroup = None
# Attribute definitions for the currect element.
self.attributeDefs = {}
self.complexType = 0
# Enumeration values for the current element.
self.values = list()
# The other simple types this is a union of.
self.unionOf = list()
self.simpleType = 0
self.listType = 0
self.documentation = ''
def setName(self, name):
self.name = name
def getName(self):
return self.name
def setBase(self, base):
self.base = base
def getBase(self):
return self.base
def setSimpleType(self, simpleType):
self.simpleType = simpleType
def getSimpleType(self):
return self.simpleType
def getAttributeGroups(self):
return self.attributeGroups
def setAttributeGroup(self, attributeGroup):
self.attributeGroup = attributeGroup
def getAttributeGroup(self):
return self.attributeGroup
def setListType(self, listType):
self.listType = listType
def isListType(self):
return self.listType
def __str__(self):
s1 = '<"%s" SimpleTypeElement instance at 0x%x>' % \
(self.getName(), id(self))
return s1
__repr__ = __str__
def resolve_list_type(self):
if self.isListType():
return 1
elif self.getBase() in SimpleTypeDict:
base = SimpleTypeDict[self.getBase()]
return base.resolve_list_type()
else:
return 0
class XschemaElement(XschemaElementBase):
def __init__(self, attrs, targetNamespace=None):
XschemaElementBase.__init__(self)
self.cleanName = ''
self.attrs = dict(attrs)
name_val = ''
type_val = ''
ref_val = ''
self.prefix = None
self.namespace = None
self.is_root_element = False
self.targetNamespace = targetNamespace
self.fullyQualifiedName = None
self.fullyQualifiedType = None
self.type = 'NoneType'
if 'name' in self.attrs:
self.prefix, name_val = get_prefix_and_value(self.attrs['name'])
self.fullyQualifiedName = "%s:%s" % (targetNamespace, name_val)
if 'type' in self.attrs:
if (len(XsdNameSpace) > 0 and
self.attrs['type'].startswith(XsdNameSpace)):
type_val = self.attrs['type']
else:
self.prefix, type_val = get_prefix_and_value(
self.attrs['type'])
self.type = type_val
if 'ref' in self.attrs:
self.prefix, ref_val = get_prefix_and_value(self.attrs['ref'])
if self.prefix in prefixToNamespaceMap:
xmlns = prefixToNamespaceMap[self.prefix]
fqn = "%s:%s" % (xmlns, ref_val)
if fqn in fqnToElementDict:
referencedElement = fqnToElementDict[fqn]
type_val = referencedElement.getType()
if type_val == "NoneType":
# anonymous types
type_val = referencedElement.getName()
name_val = ref_val
if not type_val:
type_val = ref_val
if type_val and not name_val:
name_val = type_val
if ref_val and not name_val:
name_val = ref_val
if ref_val and not type_val:
type_val = ref_val
if name_val:
self.attrs['name'] = name_val
if type_val:
self.attrs['type'] = type_val
if ref_val:
self.attrs['ref'] = ref_val
# fix_abstract
abstract_type = attrs.get('abstract', 'false').lower()
self.abstract_type = abstract_type in ('1', 'true')
self.default = self.attrs.get('default')
self.name = name_val
self.children = []
self.optional = False
self.minOccurs = 1
self.maxOccurs = 1
self.complex = 0
self.complexType = 0
self.mixed = 0
self.base = None
self.mixedExtensionError = 0
self.collapseWhiteSpace = 0
# Attribute definitions for the currect element.
self.attributeDefs = {}
# Use this to maintain predictable order of attributes.
self.attributeDefsList = []
# Attribute definitions for the current attributeGroup, if
# there is one.
self.attributeGroup = None
# List of names of attributes for this element.
# We will add the attribute defintions in each of these groups
# to this element in annotate().
self.attributeGroupNameList = []
# similar things as above, for groups of elements
self.elementGroup = None
self.topLevel = 0
# Does this element contain an anyAttribute?
self.anyAttribute = 0
self.explicit_define = 0
self.simpleType = None
# Enumeration values for the current element.
self.values = list()
# The parent choice for the current element.
self.choice = None
self.choiceGroup = None
self.listType = 0
self.simpleBase = []
self.documentation = ''
self.restrictionBase = None
self.simpleContent = False
self.extended = False
def addChild(self, element):
self.children.append(element)
def getChildren(self):
return self.children
def getName(self):
return self.name
def getFullyQualifiedName(self):
return self.fullyQualifiedName
def getFullyQualifiedType(self):
typeName = self.type
if not typeName or typeName == "NoneType":
typeName = self.name
if typeName and not self.fullyQualifiedType:
namespace = self.targetNamespace
if self.prefix and self.prefix in prefixToNamespaceMap:
xmlns = prefixToNamespaceMap[self.prefix]
if xmlns:
namespace = xmlns
self.fullyQualifiedType = "%s:%s" % (namespace, typeName)
return self.fullyQualifiedType
def getCleanName(self):
return self.cleanName
def getUnmappedCleanName(self):
return self.unmappedCleanName
def setName(self, name):
self.name = name
def getAttrs(self):
return self.attrs
def setAttrs(self, attrs):
self.attrs = attrs
def getChoiceGroup(self):
return self.choiceGroup
def setChoiceGroup(self, groupId):
self.choiceGroup = groupId
def getMinOccurs(self):
return self.minOccurs
def getMaxOccurs(self):
return self.maxOccurs
def getOptional(self):
return self.optional
def getRawType(self):
return self.type
def setExplicitDefine(self, explicit_define):
self.explicit_define = explicit_define
def isExplicitDefine(self):
return self.explicit_define
def isAbstract(self):
return self.abstract_type
def setListType(self, listType):
self.listType = listType
def isListType(self):
return self.listType
def getType(self):
returnType = self.type
if self.type in ElementDict:
typeObj = ElementDict[self.type]
typeObjType = typeObj.getRawType()
if is_builtin_simple_type(typeObjType):
returnType = typeObjType
return returnType
def isComplex(self):
return self.complex
def setIsRootElement(self, is_root_elem):
self.is_root_element = is_root_elem
def isRootElement(self):
return self.is_root_element
def addAttributeDefs(self, attrs):
self.attributeDefs.append(attrs)
def getAttributeDefs(self):
return self.attributeDefs
def getAttributeDefsList(self):
return self.attributeDefsList
def isMixed(self):
return self.mixed
def setMixed(self, mixed):
self.mixed = mixed
def setBase(self, base):
self.base = base
def getBase(self):
return self.base
def getMixedExtensionError(self):
return self.mixedExtensionError
def getAttributeGroups(self):
return self.attributeGroups
def addAttribute(self, name, attribute):
self.attributeGroups[name] = attribute
def setAttributeGroup(self, attributeGroup):
self.attributeGroup = attributeGroup
def getAttributeGroup(self):
return self.attributeGroup
def setElementGroup(self, elementGroup):
self.elementGroup = elementGroup
def getElementGroup(self):
return self.elementGroup
def setTopLevel(self, topLevel):
self.topLevel = topLevel
def getTopLevel(self):
return self.topLevel
def setAnyAttribute(self, anyAttribute):
self.anyAttribute = anyAttribute
def getAnyAttribute(self):
return self.anyAttribute
def setSimpleType(self, simpleType):
self.simpleType = simpleType
def getSimpleType(self):
return self.simpleType
def setDefault(self, default):
self.default = default
def getDefault(self):
return self.default
def getSimpleBase(self):
return self.simpleBase
def setSimpleBase(self, simpleBase):
self.simpleBase = simpleBase
def addSimpleBase(self, simpleBase):
self.simpleBase.append(simpleBase)
def getRestrictionBase(self):
return self.restrictionBase
def setRestrictionBase(self, base):
self.restrictionBase = base
def getRestrictionBaseObj(self):
rBaseObj = None
rBaseName = self.getRestrictionBase()
if rBaseName and rBaseName in ElementDict:
rBaseObj = ElementDict[rBaseName]
return rBaseObj
def setSimpleContent(self, simpleContent):
self.simpleContent = simpleContent
def getSimpleContent(self):
return self.simpleContent
def getExtended(self):
return self.extended
def setExtended(self, extended):
self.extended = extended
def show(self, outfile, level):
if self.name == 'Reference':
showLevel(outfile, level)
outfile.write('Name: %s Type: %s id: %d\n' % (
self.name, self.getType(), id(self),))
showLevel(outfile, level)
outfile.write(' - Complex: %d MaxOccurs: %d '
'MinOccurs: %d\n' % (
self.complex, self.maxOccurs, self.minOccurs))
showLevel(outfile, level)
outfile.write(' - Attrs: %s\n' % self.attrs)
showLevel(outfile, level)
#outfile.write(' - AttributeDefs: %s\n' % self.attributeDefs)
outfile.write(' - AttributeDefs:\n')
for key, value in self.getAttributeDefs().items():
showLevel(outfile, level + 1)
outfile.write('- key: %s value: %s\n' % (key, value, ))
for child in self.children:
child.show(outfile, level + 1)
def annotate(self):
# resolve group references within groups
for grp in ElementGroups.values():
expandGroupReferences(grp)
# Recursively expand group references
visited = set()
self.expandGroupReferences_tree(visited)
self.collect_element_dict()
self.annotate_find_type()
element_dict = None
to_be_removed = None
self.annotate_tree(
element_dict=element_dict,
to_be_removed=to_be_removed)
self.fix_dup_names()
self.coerce_attr_types()
self.checkMixedBases()
self.markExtendedTypes()
def markExtendedTypes(self):
base = self.getBase()
if base and base in ElementDict:
parent = ElementDict[base]
parent.setExtended(True)
for child in self.children:
child.markExtendedTypes()
def expandGroupReferences_tree(self, visited):
if self.getName() in visited:
return
visited.add(self.getName())
expandGroupReferences(self)
for child in self.children:
child.expandGroupReferences_tree(visited)
def collect_element_dict(self):
base = self.getBase()
if (self.getTopLevel() or len(self.getChildren()) > 0 or
len(self.getAttributeDefs()) > 0 or base):
ElementDict[self.name] = self
for child in self.children:
child.collect_element_dict()
def build_element_dict(self, elements):
base = self.getBase()
if (self.getTopLevel() or len(self.getChildren()) > 0 or
len(self.getAttributeDefs()) > 0 or base):
if self.name not in elements:
elements[self.name] = self
for child in self.children:
child.build_element_dict(elements)
def get_element(self, element_name):
if self.element_dict is None:
self.element_dict = dict()
self.build_element_dict(self.element_dict)
return self.element_dict.get(element_name)