-
Notifications
You must be signed in to change notification settings - Fork 0
/
Element.py
475 lines (339 loc) · 13.5 KB
/
Element.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
# $Id: Element.py,v 1.1.1.1 2008/04/20 15:03:22 elwinter Exp $
#******************************************************************************
# Import external modules.
# Standard modules.
import types
import xml.dom.minidom
# Third-party modules.
# Project modules.
#******************************************************************************
class Element:
"""Generic Element class for ModelEditor.
Description:
This is a generic Element class to represent XML elements in
ModelEditor files. This class also defines some XML-related
utilities for use by its subclasses. This is an abstract base
class, and should not be instantiated directly. All ModelEditor
element classes should inherit from this class.
Data attributes:
_tagName: (string) XML element tag name for this Element.
"""
#--------------------------------------------------------------------------
# Class constants
# Default tag name for this element.
_defaultTagName = 'element'
#--------------------------------------------------------------------------
def __init__(self,
tagName = _defaultTagName,
dom = None):
"""Initialize this Element.
Parameters:
self: This object.
tagName (string): Tag name for this element.
dom (xml.dom.minidom.Element): DOM element to convert to this
Element. If this parameter is specified, the other parameters
are ignored.
Return value:
None.
Description:
Initialize this Element. Currently, all this does is set the
_tagName data attribute.
Subclasses should call this method at the start of their own
__init__() method.
"""
# Set attributes.
if dom:
if isinstance(dom, xml.dom.minidom.Element):
self.fromDom(dom)
else:
raise TypeError('Not a DOM element (%s)!' % dom)
else:
self.setTagName(tagName)
#--------------------------------------------------------------------------
def __str__(self):
"""Return a string version of this Element.
Parameters:
self: This object.
Return value:
String representation of this Element.
Description:
Compute and return a string representation of this Element.
This is done by using the internal __dict__ attribute to get
the names and values of all data attributes. This method is
used whenever the Element is evaluated in a string context,
e.g. in a print statement. This method should work fine for
all Element subclasses.
"""
# Assemble a "key=value"-type format string for the data
# attributes. Note that dictionary lookups will be used for
# value substitution.
names = list(self.__dict__.keys())
names.sort()
attributesFormat = ','.join(['%s=%%(%s)s' % (name, name)
for name in names])
# Assemble the complete format string.
template = '%s(%s)' % (self.__class__.__name__, attributesFormat)
# Compute string values for each data attribute, and save them
# in a dictionary by attribute name.
members = {}
for k, v in iter(self.__dict__.items()):
if isinstance(v, list):
members[k] = '[' + ','.join(str(x) for x in v) + ']'
else:
members[k] = str(v)
# Populate the format string with the data attribute strings.
s = template % members
# Return the string.
return s
#--------------------------------------------------------------------------
def __eq__(self, other = None):
"""Compare this and another Element for equality.
Parameters:
self: This object.
other (Element): Element to compare against for equality.
Return value:
True if equal, False otherwise.
Description:
Compare the current Element to another Element for equality.
Used by the '==' operator. The equality check is relatively
expensive - it converts both objects to strings and compares
the strings. This was done for simplicity. A more efficient
method may be implemented later if needed. This method should
work fine for Element subclasses.
"""
# Return True if the objects are the same object.
if self is other:
return True
# Return False if the string representations are not equal.
if str(self) != str(other):
return False
# The objects are equal.
return True
def __ne__(self, other = None):
"""Compare this and another Element for inequality.
Parameters:
self: This object.
other (Element): Element to compare against for inequality.
Return value:
True if unequal, False otherwise.
Description:
Compare the current Element to another Element for inequality.
Used by the '!=' operator. The inequality check is relatively
expensive - it converts both objects to strings and compares
the strings. This was done for simplicity. A more efficient
method may be implemented later if needed. This method should
work fine for Element subclasses.
"""
# Return False if the objects are the same object.
if self is other:
return False
# Return True if the string representations are not equal.
if str(self) != str(other):
return True
# The objects are equal.
return False
#--------------------------------------------------------------------------
def toDom(self, domDocument = None):
"""Convert this Element to a xml.dom.minidom.Element.
Parameters:
self: This object.
domDocument (xml.dom.minidom.Document): DOM document to use
when converting this Element.
Return value:
xml.dom.minidom.Element for this Element.
Description:
Convert this Element to an equivalent xml.dom.minidom.Element
in the specified DOM document. For now, all this means is that
a new xml.dom.minidom.Element object with the correct tag name
is created, in the specified xml.dom.minidom.Document.
Subclasses should call this method at the start of their own
toDom() method, and then make any changes needed (usually
adding attribute and child element nodes).
"""
# Create the new DOM element with the appropriate tag name.
dom = domDocument.createElement(self.getTagName())
# Return the new DOM element.
return dom
def fromDom(self, dom = None):
"""Initialize this Element from a xml.dom.minodom.Element.
Parameters:
self: This object.
dom (xml.dom.minidom.Element): DOM element to use when
initializing this Element.
Return value:
None.
Description:
Use the specified DOM element as the source of the content of
this Element. Currently, this method only sets the tag name of
this Element.
Subclasses should call this method at the start of their own
fromDom() method, and then set the data attributes based on
any other attribute or element nodes in the DOM element.
"""
# Tag name
self.setTagName(dom.tagName)
#--------------------------------------------------------------------------
def getTagName(self):
"""Return the tag name for this Element.
Parameters:
self: This object.
Return value:
String containing the tag name for this Element.
Description:
Return the tag name for this Element as a string.
"""
return self._tagName
def setTagName(self, tagName = None):
"""Set the tag name for this Element.
Parameters:
self: This object.
tagName (string): New tag name for this Element.
Return value:
None.
Description:
Set the tag name for this Element to the specified string. If
the new tag name is invalid, raise a TypeError exception.
"""
if not self.validTagName(tagName):
raise TypeError('Invalid tag name (%s)!' % tagName)
self._tagName = tagName
def validTagName(self, tagName = None):
"""Check a tag name for validity.
Parameters:
self: This object.
tagName (string): Proposed tag name for this Element.
Return value:
True if the tag name is valid, otherwise False.
Description:
Check if the proposed new tag name is valid. A tag name is
valid if evaluates to a non-empty string.
"""
if tagName is None:
return False # str(None) = 'None'
try:
tagName = str(tagName)
except(TypeError):
return False
if tagName == '':
return False
return True
#--------------------------------------------------------------------------
def xmlBooleanToBoolean(self, boolean = None):
"""Convert a XML boolean value to a Python boolean value.
Parameters:
self: This object.
boolean (string): XML boolean value ('true', '1', 'false', or
'0').
Return value:
True if the XML boolean value represents truth, otherwise
False.
Description:
Map a XML boolean value to a Python boolean value (True or
False). XML boolean values are the strings 'true', 'false',
'1', and '0'. If the value is not a valid XML boolean value,
raise a TypeError exception.
"""
if boolean == 'true' or boolean == '1':
return True
if boolean == 'false' or boolean == '0':
return False
raise TypeError('Invalid XML boolean value (%s)!' % boolean)
def booleanToXMLBoolean(self, boolean = None, numeric = False):
"""Convert a Python boolean value to a XML boolean value.
Parameters:
self: This object.
boolean (bool): Python boolean value.
numeric (bool): Set to True to return the XML boolean value as
'1' or '0'. If not set, the XML boolean value will be returned
as 'true' or 'false'.
Return value:
String. If numeric is False, return 'true' if bool is True,
otherwise 'false'. If numeric is True, return '1' if bool is
True, otherwise '0'.
Description:
Map a Python boolean value to a XML boolean value ('true',
'false', '1', or '0'). If the value is not a valid Python
boolean value, raise a TypeError exception.
"""
if boolean == True:
if numeric:
return '1'
else:
return 'true'
if boolean == False:
if numeric:
return '0'
else:
return 'false'
raise TypeError('Invalid Python boolean value (%s)!' % boolean)
#******************************************************************************
# Self-test code.
# If this code generates any output, an error has been found.
if __name__ == '__main__':
# Default constructor.
element = Element()
assert str(element) == 'Element(_tagName=element)'
# Make the consructor fail.
try: # None for tag name
element = Element(None)
assert False
except TypeError:
pass
try: # Empty string for tag name.
element = Element('')
assert False
except TypeError:
pass
try: # None for tag name, by keyword.
element = Element(tagName = None)
assert False
except TypeError:
pass
try: # Empty string for tag name, by keyword.
element = Element(tagName = '')
assert False
except TypeError:
pass
try: # Pass a bad DOM element argument.
element = Element(dom = Element())
assert False
except TypeError:
pass
# Set/get the tag name.
element = Element()
assert element.getTagName() == 'element'
element.setTagName('anotherTest')
assert element.getTagName() == 'anotherTest'
try: # Try to use None as the tag name.
element.setTagName(None)
assert False
except TypeError:
pass
try: # Try to use an empty string as the tag name.
element.setTagName('')
assert False
except TypeError:
pass
# Constructor with attributes.
element = Element('test')
assert str(element) == 'Element(_tagName=test)'
element = Element(tagName = 'test')
assert str(element) == 'Element(_tagName=test)'
# Convert to/from DOM object, and check the '==' and '!='
# operators.
domDocument = xml.dom.minidom.Document()
dom = element.toDom(domDocument)
elementCopy = Element(dom = dom)
assert elementCopy == element
assert not (elementCopy != element)
assert element == element
assert not (element != element)
# Test the boolean conversion methods.
assert element.xmlBooleanToBoolean('true') == True
assert element.xmlBooleanToBoolean('1') == True
assert element.xmlBooleanToBoolean('false') == False
assert element.xmlBooleanToBoolean('0') == False
assert element.booleanToXMLBoolean(True) == 'true'
assert element.booleanToXMLBoolean(True, numeric = True) == '1'
assert element.booleanToXMLBoolean(False) == 'false'
assert element.booleanToXMLBoolean(False, numeric = True) == '0'