This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xe.py
2367 lines (1893 loc) · 73.7 KB
/
xe.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
# xe -- XML elements Python classes
# This is the BSD license. For more information, see:
# http://www.opensource.org/licenses/bsd-license.php
#
# Copyright (c) 2006, Steve R. Hastings
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# * Neither the name of Steve R. Hastings nor the names
# of any contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
# OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
Classes to work with XML elements in a Pythonic way.
This library module contains classes to represent XML elements.
Some important classes:
TextElement an XML element that contains text data
NestElement an XML element that contains other XML elements
Element can act like a TextElement or a NestElement
XMLDoc a container for XML element items
ListElement an XML element that holds 0 or more elements of a type
Collection a container that holds 0 or more elements of a type
XMLText a container for pieces of text not in an element
When you are nesting elements inside other elements, you give each
nested element a name; it's usually best to use the tag name value as
the name of the nested element.
Most of this module is designed for working with structured XML data,
such as syndication feed files. To work with unstructured data, you
will probably want to use a Collection of ElementItem; see the XMLText
class for more information.
Please send questions, comments, and bug reports to: [email protected]
"""
import types
module_name = "xe"
module_version = "0.7.4"
module_banner = "%s version %s" % (module_name, module_version)
def set_indent_str(s):
"""
Set the default string used to indent tags.
Arguments:
s -- string to use as the new tag indent string.
The default indent is a single tab character.
"""
global s_indent
global lst_indent
s_indent = s
lst_indent = [s_indent*i for i in range(25)]
set_indent_str("\t")
class TFC(object):
"""
TFC stands for "Tag Format Control".
A TFC controls how tags are converted to strings.
Arguments to __init__():
level Specifies what indent level to start at. Default 0.
mode Specifies how to format the output:
mode_terse -- minimal output (not indented)
mode_normal -- default output (indented)
mode_verbose -- output as much information as possible
Normally, if a nested XML item has no data, it will be left out of the
tag string; but with mode_verbose you will get an empty compact tag.
For example, if a foo tag contains a nested bar tag, and the bar tag
is empty, with mode_verbose you will get:
<foo>
<bar/>
</foo>
With mode_normal or mode_terse, you would just get: "<foo/>"
With mode_verbose on a collection, you get a comment similar to this:
<!-- collection of Author with 0 elements -->
Methods:
show_all()
Return True if TFC set to make a tag string even if the item
is blank.
terse()
Return True if TFC set for terse tag strings.
verbose()
Return True if TFC set for verbose tag strings.
indent_by(incr)
Return a TFC instance that indents by incr levels.
s_indent(extra_indent=0)
Return an indent string.
"""
mode_terse, mode_normal, mode_verbose = range(3)
def __init__(self, level=None, mode=None, tfc=None):
"""
Arguments:
level
Indent level at which to start. Default: 0
mode
How to format the output. Default: mode_normal
mode_terse -- minimal output (not indented)
mode_normal -- default output (indented)
mode_verbose -- output as much information as possible
tfc
If provided, initialize this TFC from specified tfc.
See the doc string for the whole class for examples what of
mode_verbose does for tag output.
"""
if tfc is not None:
# copy settings from another TFC
self.level = tfc.level
self.mode = tfc.mode
self.attr_sep = tfc.attr_sep
self.tag_sep = tfc.tag_sep
else:
# set defaults
self.level = 0
self.mode = TFC.mode_normal
self.attr_sep = " "
self.tag_sep = "\n"
# override defaults if arguments specified
if level is not None:
self.level = level
if mode is not None:
self.mode = mode
def show_all(self):
"""
Return True if TFC is set to show even empty elements.
Empty tags usually just don't appear in a tag string; but we
want a tag string even for an empty tag if the current level
is 0, so that if you print a tag you don't ever just get an
empty string.
And if the mode is mode_verbose, of course we always get tag
strings for everything.
The tag string code uses this to decide when to return a tag
string for an empty element, and when to return just an empty
string.
"""
return self.level == 0 or self.mode == TFC.mode_verbose
def terse(self):
"""
Return True if TFC set for terse tag strings.
Terse means there will be no indenting.
"""
return self.mode == TFC.mode_terse
def verbose(self):
"""
Return True if TFC set for verbose printing.
Normally, if an XML item has no data, nothing is printed, but with
mode_verbose you will get an empty compact tag for blank elements.
For a collection you will get a comment similar to this:
<!-- collection of Author with 0 elements -->
"""
return self.mode == TFC.mode_verbose
def indent_by(self, incr):
"""
Return a TFC instance that indents by incr levels. The mode will
be unchanged.
Pass this to a function that takes a TFC to get a temporary indent.
"""
return TFC(level=self.level + incr, tfc=self)
def s_indent(self, extra_indent=0):
"""
Return an indent string.
Return a string of white space that indents correctly for the
current TFC settings. If specified, extra_indent will be added
to the current indent level.
"""
if self.mode == TFC.mode_terse:
return ""
level = self.level + extra_indent
try:
return lst_indent[level]
except IndexError:
return s_indent * level
def attr_join(self, lst):
if self.terse():
sep = self.attr_sep
else:
# multiline attributes are treated much like tags: they are
# put on multiple lines, indented.
sep = self.tag_sep + self.s_indent(extra_indent=2)
return sep.join(lst)
def tag_join(self, lst):
return self.tag_sep.join(lst)
# Here are all of the possible XML items.
#
# Supported by xe:
# XML Declaration: <?xml ... ?>
# Comments: <!-- ... -->
# Elements: <tag_name>...</tag_name>
#
# Minimal support:
# Markup Declarations: <!KEYWORD ... >
# Processing Instructions (PIs): <?KEYWORD ... ?>
# CDATA sections: <![CDATA[ ... ]]>
#
# Not currently supported:
# INCLUDE and IGNORE directives: <!KEYWORD[ ... ]]>
class XMLItem(object):
"""
Abstract base class for all xe classes that represent XML.
All xe classes that work with XML data inherit from this
class. All it does is provide a few default methods, and be a root
for the inheritance tree.
An XMLItem has several methods that return an XML tag representation
of its contents. Each XMLItem knows how to make an XML string
representation of itself (its "tag string"). An XMLItem that
contains other XMLItems will ask each one to make a tag string; so
asking the top-level XMLItem for a tag string will cause the entire
tree of XMLItems to recursively make tag strings, and you get a full
XML representation with tags appropriately nested and indented.
"""
def _tag_not_visible(self, tfc):
if tfc.show_all():
return False
return not self
def _s_tag(self, tfc):
"""
A stub which must always be overridden by child classes.
"""
assert False, "XMLItem is an abstract class with no tag strings."
def s_tag(self, level=0):
"""
Return a tag string.
The XML tag string will be indented.
If the item is empty, and it's not a top-level item (level is
not 0), an empty string ("") will be returned. If it is a
top-level item, an empty compact tag string will be returned,
like this: <tagname/>
"""
tfc = TFC(level, TFC.mode_normal)
return self._s_tag(tfc)
def s_tag_verbose(self, level=0):
"""
Return a tag string showing all possible information.
The XML tag will be indented. All empty elements will have
empty compact tag strings like this: <tagname/>
Empty Collection elements will have an XML Comment describing
the collection.
"""
tfc = TFC(level, TFC.mode_verbose)
return self._s_tag(tfc)
def s_tag_terse(self, level=0):
"""
Return a minimal tag string without indentation.
If the item is empty, and it's not a top-level item (level is
not 0), an empty string ("") will be returned. If it is a
top-level item, an empty compact tag string will be returned,
like this: <tagname/>
"""
tfc = TFC(level, TFC.mode_terse)
return self._s_tag(tfc)
def __str__(self):
return self.s_tag()
def level(self):
"""
Return an integer describing what level this tag is.
The root tag of an XML document is level 0; document-level comments
or other document-level declarations are also level 0. Tags nested
inside the root tag are level 1, tags nested inside those tags are
level 2, and so on.
This is currently only used by the debug_tree() functions. When
printing tags normally, the code that walks the tree keeps track of
what level is current.
"""
level = 0
while self._parent != None:
self = self._parent
if isinstance(self, ElementItem):
level += 1
return level
def s_name(self):
"""
Return a name for the current item.
Used only by the debug_tree() functions.
"""
if self._name:
return self._name
return "unnamed_instance_of_" + type(self).__name__
def debug_tree(self):
"""
Return a verbose tree showing the current tag and its children.
This is for debugging; it's not valid XML syntax.
"""
level = self.level()
return "%2d) %s -- %s" % (level, self.s_name(), unicode(self))
def import_xml(self, source, lst_errors):
"""
Import XML data from source; log errors to lst_errors.
Get as much data as possible; any data that is not imported will
be appended to lst_errors, in text form.
"""
assert False, "need to overload this to actually work"
class DocItem(XMLItem):
"""
Abstract class: any XMLItem that can be document-level.
An XML document has a "root element", with all the XML elements
nested inside it; but there are some items that can appear outside
the root element, such as comments and processing instructions. All
such items inherit from this class.
"""
pass
class ElementItem(XMLItem):
"""
Abstract class: any XMLItem that can be a common element.
Basically, any XMLItem that can be inside the root element (or
can BE the root element) will inherit from this class.
"""
pass
class Comment(DocItem,ElementItem):
"""
An XML comment.
Attributes:
text -- the text of the comment
"""
def __init__(self, text=""):
"""
text -- the text of the comment
"""
self._parent = None
self._name = ""
self._direct_types = []
self.tag_name = "comment"
self.text = text
def _s_tag(self, tfc):
if self._tag_not_visible(tfc):
return ""
if self.text == "":
return tfc.s_indent() + "<!-- -->"
if self.text.find("\n") >= 0:
lst = []
lst.append(tfc.s_indent() + "<!--")
lst.append(self.text)
lst.append(tfc.s_indent() + "-->")
return tfc.tag_join(lst)
s = "%s%s%s%s" % (tfc.s_indent(), "<!-- ", self.text, " -->")
return s
def __nonzero__(self):
# Returns True if there is any comment text.
# Returns False otherwise.
return not not self.text
def text_check(self):
pass
class PI(DocItem,ElementItem):
"""
XML Processing Instruction (PI).
Attributes:
keyword
text
"""
def __init__(self, keyword, text=""):
self._parent = None
self._name = ""
self._direct_types = []
self.keyword = keyword
self.text = ""
def _s_tag(self, tfc):
if self._tag_not_visible(tfc):
return ""
if self.text.find("\n") >= 0:
lst = []
lst.append("%s%s%s" % (tfc.s_indent(), "<?", self.keyword))
lst.append(self.text)
lst.append("%s%s" % (tfc.s_indent(), "?>"))
return tfc.tag_join(lst)
s = "%s%s%s %s%s"% \
(tfc.s_indent(), "<?", self.keyword, self.text, "?>")
return s
def __nonzero__(self):
# Returns True if there is any keyword.
# Returns False otherwise.
return not not self.keyword
def text_check(self):
pass
class MarkupDecl(DocItem):
"""
XML Markup Declaration.
Used for <!ENTITY ...>, <!ATTLIST ...>, etc. declarations.
Attributes:
keyword
text
"""
def __init__(self):
self._parent = None
self._name = ""
self.keyword = ""
self.text = ""
def _s_tag(self, tfc):
if self._tag_not_visible(tfc):
return ""
# REVIEW: can I factor out a common _s_tag()?
if self.text.find("\n") >= 0:
lst = []
lst.append("%s%s%s" % (tfc.s_indent(), "<!", self.keyword))
lst.append(self.text)
lst.append("%s%s" % (tfc.s_indent(), ">"))
return tfc.tag_join(lst)
s = "%s%s%s %s%s" % \
(tfc.s_indent(), "<!", self.keyword, self.text, ">")
return s
def __nonzero__(self):
# Returns True if there is any keyword.
# Returns False otherwise.
return not not self.keyword
def text_check(self):
pass
class CDATA(DocItem):
"""
CDATA declaration.
Attributes:
text
"""
def __init__(self):
self._parent = None
self._name = ""
self.keyword = ""
self.text = ""
def _s_tag(self, tfc):
if self._tag_not_visible(tfc):
return ""
s = "%s%s%s%s" % (tfc.s_indent(), "<![CDATA[", self.text, "]]>")
return s
def __nonzero__(self):
# Returns True if there is any keyword.
# Returns False otherwise.
return not not self.keyword
def text_check(self):
pass
def _assign_compatible(o, value):
"""
Return True if value is type compatible for assigning to object o.
value is compatible with object o when:
* both o and value have the exact same type
* o is set to None
* both o and value are string types
"""
t_o = type(o)
t_val = type(value)
return t_o is t_val or \
t_o is types.NoneType or \
t_o in types.StringTypes and t_val in types.StringTypes
class Node(ElementItem):
"""
Abstract base class describing things common to nodes.
XMLText and all of the XML element classes inherit from this.
"""
def __init__(self):
self._lock = False
self._parent = None
self._name = ""
self._direct_types = []
self._lock = True
def __delattr__(self, name):
raise TypeError, "cannot delete elements"
def __getattr__(self, name):
if name == "_lock":
# If the "_lock" hasn't been created yet, we always want it
# to be False, i.e. we are not locked.
return False
else:
raise AttributeError, name
def __setattr__(self, name, value):
# Here's how this works:
#
# 0) "self._lock" is a boolean, set to False during __init__()
# but turned True afterwards. When it's False, you can add new
# members to the class instance without any sort of checks; once
# it's set True, __setattr__() starts checking assignments.
# By default, when _lock is True, you cannot add a new member to
# the class instance, and any assignment to an old member has to
# be of matching type. So if you say "a.text = string", the
# .text member has to exist and be a string member.
#
# This is the default __setattr__() for all element types. It
# gets overloaded by the __setattr__() in NestElement, because
# for nested elments, it makes sense to be able to add new
# elements nested inside.
#
# This is moderately nice. But later in class Nest there is a
# version of __setattr__() that is *very* nice; check it out.
#
# 1) This checks assignments to _parent, and makes sure they are
# plausible (either an XMLItem, or None).
try:
_lock = self._lock
except AttributeError:
_lock = False
if not _lock:
self.__dict__[name] = value
return
if not name in self.__dict__:
# brand-new item
if _lock:
raise TypeError, "element cannot nest other elements"
if name == "_parent":
if not (isinstance(value, XMLItem) or value is None):
raise TypeError, "only XMLItem or None is permitted"
self.__dict__[name] = value
return
# locked item so do checks
if not _assign_compatible(self.__dict__[name], value):
raise TypeError, \
"value's type is not compatible:" + str(type(value))
self.__dict__[name] = value
def has_contents(self):
"""
Return True if the contents are not empty.
Note that the contents could be empty but the attributes might
not be; an element is only empty if both attributs and contents
are empty.
"""
assert False, "Node is an abstract class; it has no contents."
def multiline_contents(self):
"""
Return True if the contents do not all fit on one line.
"""
assert False, "Node is an abstract class; it has no contents."
def s_contents(self, tfc):
"""
Return a string with any contents of the element.
For simple contents, just return the contents.
If the contents are nested tags, they should be correctly
indented, so this needs to take a TFC to control the indenting.
"""
assert False, "Node is an abstract class; it has no contents."
def direct(self, value):
"""
Handle direct assign of a value to the element's contents.
Some elements can handle a direct assign. Those elements need
to overload this method and make it do the right thing.
For example, you might be able to assign a time float value to a
timestamp element. In that case, the timestamp element needs to
add types.FloatType to its direct_types list, and add a
.direct() method that overloads this default one to be able to
correctly handle a float value.
"""
assert False, "cannot call Node.direct(); must subclass it"
class XMLText(Node):
"""
Class to represent simple, bare text in an XML document.
This is NOT an XML element. It has no tag name or attributes.
If you want to try working with unstructured XML data, I suggest you
create a Collection() of XMLItem() so you can tuck in all the
XMLText items and XML elements you encounter, without needing to
invent names for each one.
"""
def __init__(self, text=""):
Node.__init__(self)
self._lock = False
self.text = text
self._lock = True
def __nonzero__(self):
"""
Return True if there are any contents.
Return False otherwise.
"""
return self.text != ""
def text_check(self):
pass
def has_contents(self):
"""
Return True if the contents are not empty.
Return False otherwise.
"""
return self.text != ""
def multiline_contents(self):
"""
Return True if the contents do not all fit on one line.
"""
return self.text.find("\n") >= 0
def s_contents(self, tfc):
"""
Return a string with any contents.
"""
return self.text
def _s_tag(self, tfc):
if self.text == "":
return ""
return tfc.s_indent() + self.text
def __str__(self):
return self.text
# string constants
_s_text = "text"
_s_value = "value"
_s_tf = "tf"
_s_time_offset = "time_offset"
class Attrs(object):
"""
Class to manage a dictionary of attribute values.
Remembers in what order the attributes were assigned; when creating
a string representation of the attributes, they will always appear
in the same order.
"""
def __init__(self):
self._attrs_names = []
self._attrs_dict = {}
def __cmp__(self, o):
return cmp(self._attrs_dict, o._attrs_dict)
def __getitem__(self, k):
return self._attrs_dict[k]
def __setitem__(self, k, value):
if k not in self._attrs_dict:
# first time assigned; also update _attrs_names
self._attrs_names.append(k)
self._attrs_dict[k] = value
def __delitem__(self, k):
self._attrs_names.remove(k)
del(self._attrs_dict[k])
def __nonzero__(self):
for value in self._attrs_dict.values():
if unicode(value):
return True
return False
def lst_attrs(self):
lst = []
for name in self._attrs_names:
s_value = unicode(self._attrs_dict[name])
if s_value:
s = '%s="%s"' % (name, s_value)
lst.append(s)
return lst
def print_attrs(self):
print "Attributes:"
print " " + "\n ".join(self.lst_attrs())
def set_names(self, attr_names):
for name in attr_names:
if name not in self._attrs_dict:
self.__setitem__(name, "")
class CoreElement(Node):
"""
Abstract base class describing things common to all XML elements.
All of the XML element classes inherit from this.
"""
def __init__(self, tag_name, def_attr_name=None, def_attr_value=None,
attr_names=[], direct_types=[]):
"""
Arguments:
tag_name -- the XML tag name of this item
def_attr_name -- name of any default attribute this item has
def_attr_value -- default value of any default attribute
attr_names -- a list of expected attribute names
direct_types -- a list of types that can be direct assigned
attr_names also sets the order in which the attribute names
will be put in the tag string.
See the doc string for direct() to learn about direct_types
and direct assigns.
"""
Node.__init__(self)
self._lock = False
# dictionary of attributes and their values
self.tag_name = tag_name
self.attrs = Attrs()
if def_attr_name:
self.attrs[def_attr_name] = def_attr_value
self.attrs.set_names(attr_names)
self._direct_types = direct_types
self._lock = True
def __nonzero__(self):
"""
Return True if any attrs are set or there are any contents.
Return False otherwise.
"""
return self.attrs.__nonzero__() or self.has_contents()
def has_contents(self):
"""
Return True if the contents are not empty.
Note that the contents could be empty but the attributes might
not be; an element is only empty if both attributs and contents
are empty.
"""
assert False, "CoreElement is an abstract class; it has no contents."
def multiline_contents(self):
"""
Return True if the contents do not all fit on one line.
"""
assert False, "CoreElement is an abstract class; it has no contents."
def s_contents(self, tfc):
"""
Return a string with any contents of the element.
For simple contents, just return the contents.
If the contents are nested tags, they should be correctly
indented, so this needs to take a TFC to control the indenting.
"""
assert False, "CoreElement is an abstract class; it has no contents."
def _s_start_tag_name_attrs(self, tfc):
"""
Return a string with the start tag name, and any attributes.
Wrap this in correct angle brackets to get a start tag, or a
compact tag.
"""
lst_attrs = self.attrs.lst_attrs()
if len(lst_attrs) == 0:
return self.tag_name
if len(lst_attrs) == 1:
# just one attr so do on one line
return "%s %s" % (self.tag_name, lst_attrs[0])
# more than one attr so do a nice nested tag
assert len(lst_attrs) > 1
lst = [self.tag_name] + lst_attrs
return tfc.attr_join(lst)
def _s_tag(self, tfc):
if self._tag_not_visible(tfc):
return ""
lst = []
si = tfc.s_indent()
lst.append(si + "<" + self._s_start_tag_name_attrs(tfc))
if not self.has_contents():
lst.append("/>")
else:
if self.multiline_contents():
lst_contents = [">", self.s_contents(tfc.indent_by(1)), si]
s = tfc.tag_join(lst_contents)
lst.append(s)
else:
lst.append(">")
lst.append(self.s_contents(tfc))
lst.append("</" + self.tag_name + ">")
return "".join(lst)
def s_start_tag(self, tfc):
return tfc.s_indent() + "<" + self._s_start_tag_name_attrs(tfc) + ">"
def s_end_tag(self):
return "</" + self.tag_name + ">"
def s_compact_tag(self, tfc):
return tfc.s_indent() + "<" + self._s_start_tag_name_attrs(tfc) + "/>"
def direct(self, value):
"""
Handle direct assign of a value to the element's contents.
Some elements can handle a direct assign. Those elements need
to overload this method and make it do the right thing.
For example, you might be able to assign a time float value to a
timestamp element. In that case, the timestamp element needs to
add types.FloatType to its direct_types list, and add a
.direct() method that overloads this default one to be able to
correctly handle a float value.
"""
assert False, "cannot call CoreElement.direct(); must subclass it"
def import_xml(self, source, lst_errors=None):
"""
Import XML data from source; log errors to lst_errors.
"source" can be a filename, a URL, a string, or an xml.dom node
data structure (as returned by xml.dom.minidom.parse()).
Get as much data as possible; any data that is not imported will
be appended to lst_errors, in text form.
lst_errors is optional.
"""
return _xe_import_xml(self, source, lst_errors)
class TextElement(CoreElement):
"""
An element with simple text data.
Cannot have other elements nested inside it.
Attributes:
attrs
text
"""
def __init__(self, tag_name, text="",
def_attr_name=None, def_attr_value=None, attr_names=[]):
CoreElement.__init__(self, tag_name,
def_attr_name, def_attr_value, attr_names)
self._lock = False
self.text = text
self._lock = True
def text_check(self):
pass
def has_contents(self):
return not not self.text
def multiline_contents(self):
return self.text.find("\n") >= 0
def s_contents(self, tfc):
return self.text