Package _xmlplus ::
Package etree ::
Module ElementTree
|
|
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 __all__ = [
74
75 "Comment",
76 "dump",
77 "Element", "ElementTree",
78 "fromstring",
79 "iselement", "iterparse",
80 "parse",
81 "PI", "ProcessingInstruction",
82 "QName",
83 "SubElement",
84 "tostring",
85 "TreeBuilder",
86 "VERSION", "XML",
87 "XMLParser", "XMLTreeBuilder",
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 import string, sys, re
113
115
116 - def find(self, element, tag):
117 for elem in element:
118 if elem.tag == tag:
119 return elem
120 return None
121 - def findtext(self, element, tag, default=None):
122 for elem in element:
123 if elem.tag == tag:
124 return elem.text or ""
125 return default
127 if tag[:3] == ".//":
128 return element.getiterator(tag[3:])
129 result = []
130 for elem in element:
131 if elem.tag == tag:
132 result.append(elem)
133 return result
134
135 try:
136 import ElementPath
137 except ImportError:
138
139 ElementPath = _SimpleElementPath()
140
141
142
143
144 VERSION = "1.2.6"
145
146
147
148
149
150
151
152
153
154
155
156
157
158
160
161
162
163
164
165 tag = None
166
167
168
169
170
171
172
173
174
175 attrib = None
176
177
178
179
180
181 text = None
182
183
184
185
186
187
188 tail = None
189
194
196 return "<Element %s at %x>" % (self.tag, id(self))
197
198
199
200
201
202
203
204
207
208
209
210
211
212
214 return len(self._children)
215
216
217
218
219
220
221
222
224 return self._children[index]
225
226
227
228
229
230
231
232
233
235 assert iselement(element)
236 self._children[index] = element
237
238
239
240
241
242
243
245 del self._children[index]
246
247
248
249
250
251
252
253
255 return self._children[start:stop]
256
257
258
259
260
261
262
263
264
266 for element in elements:
267 assert iselement(element)
268 self._children[start:stop] = list(elements)
269
270
271
272
273
274
275
277 del self._children[start:stop]
278
279
280
281
282
283
284
286 assert iselement(element)
287 self._children.append(element)
288
289
290
291
292
293
294
295 - def insert(self, index, element):
296 assert iselement(element)
297 self._children.insert(index, element)
298
299
300
301
302
303
304
305
306
307
309 assert iselement(element)
310 self._children.remove(element)
311
312
313
314
315
316
317
318
320 return self._children
321
322
323
324
325
326
327
328
329 - def find(self, path):
330 return ElementPath.find(self, path)
331
332
333
334
335
336
337
338
339
340
341
342
343 - def findtext(self, path, default=None):
344 return ElementPath.findtext(self, path, default)
345
346
347
348
349
350
351
352
353
355 return ElementPath.findall(self, path)
356
357
358
359
360
362 self.attrib.clear()
363 self._children = []
364 self.text = self.tail = None
365
366
367
368
369
370
371
372
373
374
375 - def get(self, key, default=None):
376 return self.attrib.get(key, default)
377
378
379
380
381
382
383
384 - def set(self, key, value):
386
387
388
389
390
391
392
393
396
397
398
399
400
401
402
403
405 return self.attrib.items()
406
407
408
409
410
411
412
413
414
415
416
417
418
420 nodes = []
421 if tag == "*":
422 tag = None
423 if tag is None or self.tag == tag:
424 nodes.append(self)
425 for node in self._children:
426 nodes.extend(node.getiterator(tag))
427 return nodes
428
429
430 _Element = _ElementInterface
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447 -def Element(tag, attrib={}, **extra):
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
467 attrib = attrib.copy()
468 attrib.update(extra)
469 element = parent.makeelement(tag, attrib)
470 parent.append(element)
471 return element
472
473
474
475
476
477
478
479
480
481
482
483
488
489
490
491
492
493
494
495
496
497
499 element = Element(ProcessingInstruction)
500 element.text = target
501 if text:
502 element.text = element.text + " " + text
503 return element
504
505 PI = ProcessingInstruction
506
507
508
509
510
511
512
513
514
515
516
518 - def __init__(self, text_or_uri, tag=None):
519 if tag:
520 text_or_uri = "{%s}%s" % (text_or_uri, tag)
521 self.text = text_or_uri
525 return hash(self.text)
527 if isinstance(other, QName):
528 return cmp(self.text, other.text)
529 return cmp(self.text, other)
530
531
532
533
534
535
536
537
538
539
541
542 - def __init__(self, element=None, file=None):
543 assert element is None or iselement(element)
544 self._root = element
545 if file:
546 self.parse(file)
547
548
549
550
551
552
553
556
557
558
559
560
561
562
563
565 assert iselement(element)
566 self._root = element
567
568
569
570
571
572
573
574
575
576
577 - def parse(self, source, parser=None):
578 if not hasattr(source, "read"):
579 source = open(source, "rb")
580 if not parser:
581 parser = XMLTreeBuilder()
582 while 1:
583 data = source.read(32768)
584 if not data:
585 break
586 parser.feed(data)
587 self._root = parser.close()
588 return self._root
589
590
591
592
593
594
595
596
597
599 assert self._root is not None
600 return self._root.getiterator(tag)
601
602
603
604
605
606
607
608
609
610 - def find(self, path):
611 assert self._root is not None
612 if path[:1] == "/":
613 path = "." + path
614 return self._root.find(path)
615
616
617
618
619
620
621
622
623
624
625
626
627
628 - def findtext(self, path, default=None):
629 assert self._root is not None
630 if path[:1] == "/":
631 path = "." + path
632 return self._root.findtext(path, default)
633
634
635
636
637
638
639
640
641
642
644 assert self._root is not None
645 if path[:1] == "/":
646 path = "." + path
647 return self._root.findall(path)
648
649
650
651
652
653
654
655 - def write(self, file, encoding="us-ascii"):
656 assert self._root is not None
657 if not hasattr(file, "write"):
658 file = open(file, "wb")
659 if not encoding:
660 encoding = "us-ascii"
661 elif encoding != "utf-8" and encoding != "us-ascii":
662 file.write("<?xml version='1.0' encoding='%s'?>\n" % encoding)
663 self._write(file, self._root, encoding, {})
664
665 - def _write(self, file, node, encoding, namespaces):
666
667 tag = node.tag
668 if tag is Comment:
669 file.write("<!-- %s -->" % _escape_cdata(node.text, encoding))
670 elif tag is ProcessingInstruction:
671 file.write("<?%s?>" % _escape_cdata(node.text, encoding))
672 else:
673 items = node.items()
674 xmlns_items = []
675 try:
676 if isinstance(tag, QName) or tag[:1] == "{":
677 tag, xmlns = fixtag(tag, namespaces)
678 if xmlns: xmlns_items.append(xmlns)
679 except TypeError:
680 _raise_serialization_error(tag)
681 file.write("<" + _encode(tag, encoding))
682 if items or xmlns_items:
683 items.sort()
684 for k, v in items:
685 try:
686 if isinstance(k, QName) or k[:1] == "{":
687 k, xmlns = fixtag(k, namespaces)
688 if xmlns: xmlns_items.append(xmlns)
689 except TypeError:
690 _raise_serialization_error(k)
691 try:
692 if isinstance(v, QName):
693 v, xmlns = fixtag(v, namespaces)
694 if xmlns: xmlns_items.append(xmlns)
695 except TypeError:
696 _raise_serialization_error(v)
697 file.write(" %s=\"%s\"" % (_encode(k, encoding),
698 _escape_attrib(v, encoding)))
699 for k, v in xmlns_items:
700 file.write(" %s=\"%s\"" % (_encode(k, encoding),
701 _escape_attrib(v, encoding)))
702 if node.text or len(node):
703 file.write(">")
704 if node.text:
705 file.write(_escape_cdata(node.text, encoding))
706 for n in node:
707 self._write(file, n, encoding, namespaces)
708 file.write("</" + _encode(tag, encoding) + ">")
709 else:
710 file.write(" />")
711 for k, v in xmlns_items:
712 del namespaces[v]
713 if node.tail:
714 file.write(_escape_cdata(node.tail, encoding))
715
716
717
718
719
720
721
722
723
724
725
730
731
732
733
734
735
736
737
738
739
741
742 if not isinstance(elem, ElementTree):
743 elem = ElementTree(elem)
744 elem.write(sys.stdout)
745 tail = elem.getroot().tail
746 if not tail or tail[-1] != "\n":
747 sys.stdout.write("\n")
748
750 try:
751 return s.encode(encoding)
752 except AttributeError:
753 return s
754
755 if sys.version[:3] == "1.5":
756 _escape = re.compile(r"[&<>\"\x80-\xff]+")
757 else:
758 _escape = re.compile(eval(r'u"[&<>\"\u0080-\uffff]+"'))
759
760 _escape_map = {
761 "&": "&",
762 "<": "<",
763 ">": ">",
764 '"': """,
765 }
766
767 _namespace_map = {
768
769 "http://www.w3.org/XML/1998/namespace": "xml",
770 "http://www.w3.org/1999/xhtml": "html",
771 "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
772 "http://schemas.xmlsoap.org/wsdl/": "wsdl",
773 }
774
776 raise TypeError(
777 "cannot serialize %r (type %s)" % (text, type(text).__name__)
778 )
779
781
782 def escape_entities(m, map=_escape_map):
783 out = []
784 append = out.append
785 for char in m.group():
786 text = map.get(char)
787 if text is None:
788 text = "&#%d;" % ord(char)
789 append(text)
790 return string.join(out, "")
791 try:
792 return _encode(pattern.sub(escape_entities, text), "ascii")
793 except TypeError:
794 _raise_serialization_error(text)
795
796
797
798
799
801
802 try:
803 if encoding:
804 try:
805 text = _encode(text, encoding)
806 except UnicodeError:
807 return _encode_entity(text)
808 text = replace(text, "&", "&")
809 text = replace(text, "<", "<")
810 text = replace(text, ">", ">")
811 return text
812 except (TypeError, AttributeError):
813 _raise_serialization_error(text)
814
816
817 try:
818 if encoding:
819 try:
820 text = _encode(text, encoding)
821 except UnicodeError:
822 return _encode_entity(text)
823 text = replace(text, "&", "&")
824 text = replace(text, "'", "'")
825 text = replace(text, "\"", """)
826 text = replace(text, "<", "<")
827 text = replace(text, ">", ">")
828 return text
829 except (TypeError, AttributeError):
830 _raise_serialization_error(text)
831
833
834
835 if isinstance(tag, QName):
836 tag = tag.text
837 namespace_uri, tag = string.split(tag[1:], "}", 1)
838 prefix = namespaces.get(namespace_uri)
839 if prefix is None:
840 prefix = _namespace_map.get(namespace_uri)
841 if prefix is None:
842 prefix = "ns%d" % len(namespaces)
843 namespaces[namespace_uri] = prefix
844 if prefix == "xml":
845 xmlns = None
846 else:
847 xmlns = ("xmlns:%s" % prefix, namespace_uri)
848 else:
849 xmlns = None
850 return "%s:%s" % (prefix, tag), xmlns
851
852
853
854
855
856
857
858
859
860 -def parse(source, parser=None):
864
865
866
867
868
869
870
871
872
873
875
876 - def __init__(self, source, events=None):
877 if not hasattr(source, "read"):
878 source = open(source, "rb")
879 self._file = source
880 self._events = []
881 self._index = 0
882 self.root = self._root = None
883 self._parser = XMLTreeBuilder()
884
885 parser = self._parser._parser
886 append = self._events.append
887 if events is None:
888 events = ["end"]
889 for event in events:
890 if event == "start":
891 try:
892 parser.ordered_attributes = 1
893 parser.specified_attributes = 1
894 def handler(tag, attrib_in, event=event, append=append,
895 start=self._parser._start_list):
896 append((event, start(tag, attrib_in)))
897 parser.StartElementHandler = handler
898 except AttributeError:
899 def handler(tag, attrib_in, event=event, append=append,
900 start=self._parser._start):
901 append((event, start(tag, attrib_in)))
902 parser.StartElementHandler = handler
903 elif event == "end":
904 def handler(tag, event=event, append=append,
905 end=self._parser._end):
906 append((event, end(tag)))
907 parser.EndElementHandler = handler
908 elif event == "start-ns":
909 def handler(prefix, uri, event=event, append=append):
910 try:
911 uri = _encode(uri, "ascii")
912 except UnicodeError:
913 pass
914 append((event, (prefix or "", uri)))
915 parser.StartNamespaceDeclHandler = handler
916 elif event == "end-ns":
917 def handler(prefix, event=event, append=append):
918 append((event, None))
919 parser.EndNamespaceDeclHandler = handler
920
922 while 1:
923 try:
924 item = self._events[self._index]
925 except IndexError:
926 if self._parser is None:
927 self.root = self._root
928 try:
929 raise StopIteration
930 except NameError:
931 raise IndexError
932
933 del self._events[:]
934 self._index = 0
935 data = self._file.read(16384)
936 if data:
937 self._parser.feed(data)
938 else:
939 self._root = self._parser.close()
940 self._parser = None
941 else:
942 self._index = self._index + 1
943 return item
944
945 try:
946 iter
949 except NameError:
952
953
954
955
956
957
958
959
960
965
966
967
968
969
970
971
972
973
975 parser = XMLTreeBuilder()
976 parser.feed(text)
977 tree = parser.close()
978 ids = {}
979 for elem in tree.getiterator():
980 id = elem.get("id")
981 if id:
982 ids[id] = elem
983 return tree, ids
984
985
986
987
988
989
990
991
992
993 fromstring = XML
994
995
996
997
998
999
1000
1001
1002
1004 class dummy:
1005 pass
1006 data = []
1007 file = dummy()
1008 file.write = data.append
1009 ElementTree(element).write(file, encoding)
1010 return string.join(data, "")
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1024
1025 - def __init__(self, element_factory=None):
1026 self._data = []
1027 self._elem = []
1028 self._last = None
1029 self._tail = None
1030 if element_factory is None:
1031 element_factory = _ElementInterface
1032 self._factory = element_factory
1033
1034
1035
1036
1037
1038
1039
1040
1042 assert len(self._elem) == 0, "missing end tags"
1043 assert self._last != None, "missing toplevel element"
1044 return self._last
1045
1047 if self._data:
1048 if self._last is not None:
1049 text = string.join(self._data, "")
1050 if self._tail:
1051 assert self._last.tail is None, "internal error (tail)"
1052 self._last.tail = text
1053 else:
1054 assert self._last.text is None, "internal error (text)"
1055 self._last.text = text
1056 self._data = []
1057
1058
1059
1060
1061
1062
1063
1064 - def data(self, data):
1065 self._data.append(data)
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075 - def start(self, tag, attrs):
1076 self._flush()
1077 self._last = elem = self._factory(tag, attrs)
1078 if self._elem:
1079 self._elem[-1].append(elem)
1080 self._elem.append(elem)
1081 self._tail = 0
1082 return elem
1083
1084
1085
1086
1087
1088
1089
1090
1091 - def end(self, tag):
1092 self._flush()
1093 self._last = self._elem.pop()
1094 assert self._last.tag == tag,\
1095 "end tag mismatch (expected %s, got %s)" % (
1096 self._last.tag, tag)
1097 self._tail = 1
1098 return self._last
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1112
1113 - def __init__(self, html=0, target=None):
1114 try:
1115 from xml.parsers import expat
1116 except ImportError:
1117 raise ImportError(
1118 "No module named expat; use SimpleXMLTreeBuilder instead"
1119 )
1120 self._parser = parser = expat.ParserCreate(None, "}")
1121 if target is None:
1122 target = TreeBuilder()
1123 self._target = target
1124 self._names = {}
1125
1126 parser.DefaultHandlerExpand = self._default
1127 parser.StartElementHandler = self._start
1128 parser.EndElementHandler = self._end
1129 parser.CharacterDataHandler = self._data
1130
1131 try:
1132 self._parser.buffer_text = 1
1133 except AttributeError:
1134 pass
1135
1136 try:
1137 self._parser.ordered_attributes = 1
1138 self._parser.specified_attributes = 1
1139 parser.StartElementHandler = self._start_list
1140 except AttributeError:
1141 pass
1142 encoding = None
1143 if not parser.returns_unicode:
1144 encoding = "utf-8"
1145
1146 self._doctype = None
1147 self.entity = {}
1148
1149 - def _fixtext(self, text):
1150
1151 try:
1152 return _encode(text, "ascii")
1153 except UnicodeError:
1154 return text
1155
1157
1158 try:
1159 name = self._names[key]
1160 except KeyError:
1161 name = key
1162 if "}" in name:
1163 name = "{" + name
1164 self._names[key] = name = self._fixtext(name)
1165 return name
1166
1167 - def _start(self, tag, attrib_in):
1168 fixname = self._fixname
1169 tag = fixname(tag)
1170 attrib = {}
1171 for key, value in attrib_in.items():
1172 attrib[fixname(key)] = self._fixtext(value)
1173 return self._target.start(tag, attrib)
1174
1176 fixname = self._fixname
1177 tag = fixname(tag)
1178 attrib = {}
1179 if attrib_in:
1180 for i in range(0, len(attrib_in), 2):
1181 attrib[fixname(attrib_in[i])] = self._fixtext(attrib_in[i+1])
1182 return self._target.start(tag, attrib)
1183
1185 return self._target.data(self._fixtext(text))
1186
1187 - def _end(self, tag):
1188 return self._target.end(self._fixname(tag))
1189
1191 prefix = text[:1]
1192 if prefix == "&":
1193
1194 try:
1195 self._target.data(self.entity[text[1:-1]])
1196 except KeyError:
1197 from xml.parsers import expat
1198 raise expat.error(
1199 "undefined entity %s: line %d, column %d" %
1200 (text, self._parser.ErrorLineNumber,
1201 self._parser.ErrorColumnNumber)
1202 )
1203 elif prefix == "<" and text[:9] == "<!DOCTYPE":
1204 self._doctype = []
1205 elif self._doctype is not None:
1206
1207 if prefix == ">":
1208 self._doctype = None
1209 return
1210 text = string.strip(text)
1211 if not text:
1212 return
1213 self._doctype.append(text)
1214 n = len(self._doctype)
1215 if n > 2:
1216 type = self._doctype[1]
1217 if type == "PUBLIC" and n == 4:
1218 name, type, pubid, system = self._doctype
1219 elif type == "SYSTEM" and n == 3:
1220 name, type, system = self._doctype
1221 pubid = None
1222 else:
1223 return
1224 if pubid:
1225 pubid = pubid[1:-1]
1226 self.doctype(name, pubid, system[1:-1])
1227 self._doctype = None
1228
1229
1230
1231
1232
1233
1234
1235
1236 - def doctype(self, name, pubid, system):
1238
1239
1240
1241
1242
1243
1244 - def feed(self, data):
1245 self._parser.Parse(data, 0)
1246
1247
1248
1249
1250
1251
1252
1254 self._parser.Parse("", 1)
1255 tree = self._target.close()
1256 del self._target, self._parser
1257 return tree
1258
1259
1260 XMLParser = XMLTreeBuilder
1261