-
Notifications
You must be signed in to change notification settings - Fork 0
/
pxdom.py
5700 lines (5081 loc) · 211 KB
/
pxdom.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
"""pxdom - stand-alone embeddable pure-Python DOM implementation
Fully-compliant with DOM Level 3 Core/XML and Load/Save Recommendations.
Includes pure-Python non-validating parser.
"""
__version__= 1,6
__author__= 'Andrew Clover <[email protected]>'
__date__= 2008,5,1
__all__= ['getDOMImplementation', 'getDOMImplementations', 'parse', 'parseString', 'DOMException']
# Setup, utility functions
# ============================================================================
import os, string, StringIO, urlparse, urllib, httplib
r= string.replace
def _insertMethods():
"""Monkey-patch specially-named methods into classes
In this source, not all members are defined directly inside their class
definitions; some are organised into aspects and defined together later
in the file, to improve readability. This function is called at the end to
combine the externally-defined members, whose names are in the format
_class__member, into the classes they are meant to be in.
"""
for key, value in globals().items():
if key[:1]=='_' and string.find(key, '__')>=1:
class_, method= string.split(key[1:], '__', 1)
setattr(globals()[class_], method, value)
# Backwards-compatibility boolean type (<2.2.1)
#
try:
True
except NameError:
globals()['True'], globals()['False']= None is None, None is not None
# Use sets where available for low-level character matching
#
try:
from sets import ImmutableSet
except ImportError:
ImmutableSet= lambda x: x
# Check unicode is supported (Python 1.6+), provide dummy class to use with
# isinstance
#
try:
import unicodedata
except ImportError:
globals()['unicode']= None
class Unicode: pass
else:
Unicode= type(unicode(''))
import unicodedata, codecs
# Allow thread-specific storage when threading is available
#
try:
from thread import get_ident
except ImportError:
get_ident= lambda: None
# XML character classes. Provide only an XML 1.1 character model for NAMEs, as
# 1.0's rules are insanely complex.
#
DEC= ImmutableSet('0123456789')
HEX= ImmutableSet('0123456789abcdefABDCDEF')
LS= ('\r\n', '\r')
WHITE= ' \t\n\r'
NOTCHAR= ImmutableSet('\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0B\x0C\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x7F')
NOTFIRST= ImmutableSet('.-0123456789')
NOTNAME= ImmutableSet(' \t\n\r!"#$%&\'()*+,/;<=>?@[\\]^`{|}~')
NOTURI= ImmutableSet(
string.join(map(chr, range(0, 33)+range(127,256)), '')+'<>"{}\^`'
)
if unicode is not None:
LSU= unichr(0x85), unichr(0x2028)
WHITEU= unichr(0x85)+unichr(0x2028)
NOTCHARU= ImmutableSet(
unicode('\x80\x81\x82\x83\x84\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F', 'iso-8859-1')
+unichr(0xFFFE)+unichr(0xFFFF)
)
NOTFIRSTU= (0xB7,0xB8), (0x300,0x370), (0x203F,0x2041)
NOTNAMEU= (
(0x80,0xB7), (0xB8,0xC0), (0xD7,0xD8), (0xF7,0xF8), (0x037E,0x037F), (0x2000,0x200C), (0x200E,0x203F),
(0x2041,0x2070), (0x2190,0x2C00), (0x2FF0,0x3001), (0xE000,0xF900), (0xFDD0,0xFDF0), (0xFFFE, 0x10000)
)
# Unicode character normalisation (>=2.3). Also includes a kludge for
# composing-characters that we can't check through unicodedata, see
# 'Character Model for the World Wide Web', Appendix C
#
CNORM= False
if unicode is not None:
if hasattr(unicodedata, 'normalize'):
CNORM= True
EXTRACOMPOSERS= string.join(map(unichr, [
0x09BE, 0x09D7, 0x0B3E, 0x0B56, 0x0B57, 0x0BBE, 0x0BD7, 0x0CC2, 0x0CD5,
0x0CD6, 0x0D3E, 0x0D57, 0x0DCF, 0x0DDF, 0x0FB5, 0x0FB7, 0x102E
] + range(0x1161, 0x1176) + range(0x11A8, 0x11C2) ), '')
def dictadd(a, b):
ab= a.copy()
ab.update(b)
return ab
REPR_MAX_LEN= 12
REPR_MAX_LIST=3
# Special namespace URIs
#
XMNS= 'http://www.w3.org/XML/1998/namespace'
NSNS= 'http://www.w3.org/2000/xmlns/'
HTNS= 'http://www.w3.org/1999/xhtml'
DTNS= 'http://www.w3.org/TR/REC-xml'
FIXEDNS= {'xmlns': NSNS, 'xml': XMNS}
class _NONS:
"""No-namespaces special value
Singleton value type used internally as a value for namespaceURI
signifying that a non-namespace version of a node or method is in use;
the accompanying localName is then the complete nodeName. This is
different to None, which is a null namespace value.
"""
def __str__(self):
return '(non-namespace)'
NONS= _NONS()
# Media types to allow in addition to anything labelled '...+xml' when using
# parameter supported-media-types-only
#
XMLTYPES= [
'text/xml', 'application/xml', 'application/xml-dtd', 'text/xsl'
'text/xml-external-parsed-entity','application/xml-external-parsed-entity'
]
# Elements defined as EMPTY in XHTML for parameter pxdom-html-compatible
#
HTMLEMPTY= [
'area', 'base', 'basefont', 'br', 'col', 'frame', 'hr', 'img',
'input', 'isindex', 'link', 'meta', 'param'
]
def _checkName(name, nc= False):
"""Check name string, raise exception if not well-formed
Optionally check it also matches NCName (no colons)
"""
if name=='':
raise InvalidCharacterErr(name, '')
if name[0] in NOTFIRST:
raise InvalidCharacterErr(name, name[0])
if isinstance(name, Unicode):
for c0, c1 in NOTFIRSTU:
if ord(name[0])>=c0 and ord(name[0])<c1:
raise InvalidCharacterErr(name, name[0])
for char in name:
if char in NOTNAME or char in NOTCHAR:
raise InvalidCharacterErr(name, char)
if isinstance(char, Unicode):
if char in NOTCHARU:
raise InvalidCharacterErr(name, char)
for c0, c1 in NOTNAMEU:
if ord(char)>=c0 and ord(char)<c1:
raise InvalidCharacterErr(name, char)
if nc and ':' in name:
raise NamespaceErr(name, None)
def _splitName(name):
"""Split a qualified name into prefix and localName
prefix may be None if no prefix is used; both will be None if the name
is not a valid qualified name.
"""
parts= string.split(name, ':', 2)
if '' not in parts:
if len(parts)==2:
return tuple(parts)
if len(parts)==1:
return (None, name)
return (None, None)
def _encodeURI(s):
"""Turn a string from a SYSTEM ID or xml:base attribute into a URI string
%-encode disallowed characters
"""
if isinstance(s, Unicode):
s= s.encode('utf-8')
uri= ''
for c in s:
if c in NOTURI:
uri= uri+'%%%02X'%ord(c)
else:
uri= uri+c
return uri
class DOMObject:
"""Base class for objects implementing DOM interfaces
Provide properties in a way compatible with old versions of Python:
subclass should provide method _get_propertyName to make a read-only
property, and also _set_propertyName for a writable. If the readonly
property is set, all other properties become immutable.
"""
def __init__(self, readonly= False):
self._readonly= readonly
def _get_readonly(self):
return self._readonly
def _set_readonly(self, value):
self._readonly= value
def __getattr__(self, key):
if key[:1]=='_':
raise AttributeError, key
try:
getter= getattr(self, '_get_'+key)
except AttributeError:
raise AttributeError, key
return getter()
def __setattr__(self, key, value):
if key[:1]=='_':
self.__dict__[key]= value
return
# When an object is readonly, there are a few attributes that can be set
# regardless. Readonly is one (obviously), but due to a wart in the DOM
# spec it must also be possible to set nodeValue and textContent to
# anything on nodes where these properties are defined to be null (with no
# effect). Check specifically for these property names as a nasty hack
# to conform exactly to the spec.
#
if self._readonly and key not in ('readonly', 'nodeValue', 'textContent'):
raise NoModificationAllowedErr(self, key)
try:
setter= getattr(self, '_set_'+key)
except AttributeError:
if hasattr(self, '_get_'+key):
raise NoModificationAllowedErr(self, key)
raise AttributeError, key
setter(value)
# Node-structure classes
# ============================================================================
class DOMList(DOMObject):
"""Sequence that responds to Python and DOM-style access
"""
def __init__(self, initial= None):
DOMObject.__init__(self)
if initial is None:
self._list= []
else:
self._list= initial
def __repr__(self):
l= repr(self._list[:REPR_MAX_LIST])
if len(self._list)>REPR_MAX_LIST:
l= l+'...'
return '<pxdom.%s %s>' % (self.__class__.__name__, l)
# DOM-style methods
#
def _get_length(self):
return len(self._list)
def item(self, index):
if index<0 or index>=len(self._list):
return None
return self._list[index]
def contains(self, str):
return str in self._list
# Python-style methods
#
def __len__(self):
return len(self._list)
def __getitem__(self, index):
return self._list[index]
def __setitem__(self, index, value):
raise NoModificationAllowedErr(self, 'item(%s)' % str(index))
def __delitem__(self, index):
raise NoModificationAllowedErr(self, 'item(%s)' % str(index))
# Mutable sequence convenience methods for internal use
#
def _index(self, value):
return self._list.index(value)
def _append(self, value):
if self._readonly:
raise NoModificationAllowedErr(self, 'item(%s)' % str(len(self._list)))
self._list.append(value)
def _insertseq(self, index, values):
if self._readonly:
raise NoModificationAllowedErr(self, 'item(%s)' % str(index))
self._list[index:index]= values
class NodeList(DOMList):
"""Abstract list of nodes dependent on an owner node.
"""
def __init__(self, ownerNode= None):
DOMList.__init__(self)
self._ownerNode= ownerNode
class ChildNodeList(NodeList):
"""NodeList of children of a parent node
Python-style alterations to the list result in calls to the parent's
corresponding DOM methods. This seems to be required by a literal reading of
the Python DOM bindings spec, but tends not to be relied on in practice.
"""
def __setitem__(self, index, value):
self._ownerNode.replaceChild(value, self._list[index])
def __delitem__(self, index):
self._ownerNode.removeChild(self._list[index])
class NodeListByTagName(NodeList):
"""Live NodeList returned by Element.getElementsByTagName[NS] methods
As a 'live' list, the internal _list acts only as a cache, and is
recalculated if the owner Element's contents have changed since it was
last built.
"""
def __init__(self, ownerNode, namespaceURI, localName):
NodeList.__init__(self, ownerNode)
self._namespaceURI= namespaceURI
self._localName= localName
self._sequence= None
def _get_length(self):
if self._sequence!=self._ownerNode._sequence: self._calculate()
return NodeList._get_length(self)
def item(self, index):
if self._sequence!=self._ownerNode._sequence: self._calculate()
return NodeList.item(self, index)
def __getitem__(self, index):
if self._sequence!=self._ownerNode._sequence: self._calculate()
return NodeList.__getitem__(self, index)
def __len__(self):
if self._sequence!=self._ownerNode._sequence: self._calculate()
return NodeList.__len__(self)
def __repr__(self):
try:
self._calculate()
except DOMException:
pass
return NodeList.__repr__(self)
def _calculate(self):
"""Recalculate the list
This method does the actual work of the getElementsByTagName call
"""
self._list= []
self._walk(self._ownerNode)
self._sequence= self._ownerNode._sequence
def _walk(self, element):
"""Recurse through child elements looking for matches
"""
for childNode in element.childNodes:
if childNode.nodeType==Node.ELEMENT_NODE:
if (
self._localName=='*' and
self._namespaceURI in ('*', NONS, childNode.namespaceURI)
) or (
self._namespaceURI=='*' and
self._localName==childNode.localName
) or (
self._namespaceURI is NONS and
self._localName==childNode.nodeName
) or (
self._namespaceURI==childNode.namespaceURI and
self._localName==childNode.localName
):
self._list.append(childNode)
if childNode.nodeType in (Node.ELEMENT_NODE,Node.ENTITY_REFERENCE_NODE):
self._walk(childNode)
class NamedNodeMap(NodeList):
"""Abstract dictionary-style object used for mappings
Subclass should initialise with the nodeType for nodes it is intending to
hold as values.
"""
def __init__(self, ownerNode, childType):
NodeList.__init__(self, ownerNode)
self._childTypes= (childType,)
def getNamedItemNS(self, namespaceURI, localName):
if namespaceURI=='':
namespaceURI= None
for node in self._list:
if (
(namespaceURI is NONS and localName==node.nodeName) or
(namespaceURI==node.namespaceURI and localName==node.localName)
):
return node
return None
def setNamedItemNS(self, arg):
node= self.getNamedItemNS(arg.namespaceURI, arg.localName)
self._writeItem(node, arg)
return node
def removeNamedItemNS(self, namespaceURI, localName):
node= self.getNamedItemNS(namespaceURI, localName)
if node is None:
raise NotFoundErr(self, namespaceURI, localName)
self._writeItem(node, None)
return node
def getNamedItem(self, name):
return self.getNamedItemNS(NONS, name)
def setNamedItem(self, arg):
node= self.getNamedItemNS(NONS, arg.nodeName)
self._writeItem(node, arg)
return node
def removeNamedItem(self, name):
return self.removeNamedItemNS(NONS, name)
def _writeItem(self, oldItem, newItem):
"""Internal backend for all add/remove/replace operations
If oldItem is not None it is removed; if newItem is not None it is
added; if both are not None the new item is written to the previous
position of the oldItem.
"""
if self._readonly:
raise NoModificationAllowedErr(self, 'namedItem')
if newItem is not None:
if newItem.nodeType not in self._childTypes:
raise HierarchyRequestErr(newItem, self)
if newItem.ownerDocument is not self._ownerNode.ownerDocument:
raise WrongDocumentErr(self._ownerNode.ownerDocument, newItem)
if oldItem is None:
index= len(self._list)
else:
try:
index= self._list.index(oldItem)
except ValueError:
raise NotFoundErr(self, NONS, oldItem.nodeName)
oldItem._containerNode= None
if newItem is not None:
newItem._containerNode= self._ownerNode
self._list[index:index+1]= [newItem]
else:
self._list[index:index+1]= []
# Python dictionary-style methods. This is inconsistent with how Python
# dictionaries normally work; it is only here for compatibility with
# minidom and the behaviour is not guaranteed. Use the standard DOM methods
# getNamedItem etc. instead.
#
def __getitem__(self, key):
if isinstance(key, type(0)):
return self._list[key]
elif isinstance(key, type(())):
return self.getNamedItemNS(key[0], key[1])
else:
return self.getNamedItem(key)
def __delitem__(self, key):
if isinstance(key, type(0)):
self._writeItem(self._list[key], None)
elif isinstance(key, type(())):
self.removeNamedItemNS(key[0], key[1])
else:
return self.removeNamedItem(key)
def __setitem__(self, key, value):
if isinstance(value, Attr):
if isinstance(key, type(0)):
self._writeItem(self._list[key], value)
elif isinstance(key, type(())):
self._ownerNode.setAttributeNodeNS(value)
else:
self._ownerNode.setAttributeNode(value)
else:
if isinstance(key, type(0)):
self._list[key].value= value
elif isinstance(key, type(())):
return self._ownerNode.setAttributeNS(key[0], key[1], value)
else:
return self._ownerNode.setAttribute(key, value)
def values(self):
return self._list[:]
def keys(self):
return map(lambda a: a.nodeName, self._list)
def items(self):
return map(lambda a: (a.nodeName, a.value), self._list)
def keysNS(self):
return map(lambda a: (a.namespaceURI, a.localName), self._list)
def itemsNS(self):
return map(lambda a: ((a.namespaceURI,a.localName),a.value), self._list)
class AttrMap(NamedNodeMap):
"""A node mapping for an Element's attributes
Defaulted attributes are updated automatically on changes.
"""
def __init__(self, ownerNode):
NamedNodeMap.__init__(self, ownerNode, Node.ATTRIBUTE_NODE)
def _writeItem(self, oldItem, newItem):
if newItem is not None and newItem.nodeType==Node.ATTRIBUTE_NODE and (
newItem._containerNode not in (None, self._ownerNode)
):
raise InuseAttributeErr(newItem)
NamedNodeMap._writeItem(self, oldItem, newItem)
if oldItem is not None:
if newItem is None or newItem.nodeName!=oldItem.nodeName:
ownerDocument= self._ownerNode.ownerDocument
if ownerDocument is not None:
doctype= ownerDocument.doctype
if doctype is not None:
declarationList= doctype._attlists.getNamedItem(
self._ownerNode.nodeName
)
if declarationList is not None:
declaration= declarationList.declarations.getNamedItem(oldItem.nodeName)
if (declaration is not None and declaration.defaultType in (
AttributeDeclaration.DEFAULT_VALUE, AttributeDeclaration.FIXED_VALUE
)):
declaration._createAttribute(self._ownerNode)
# Core non-node classes
# ============================================================================
class DOMImplementation(DOMObject):
"""Main pxdom implementation interface
The pxdom module itself implements the DOMImplementationSource interface,
so you can get hold of the module's singleton implementation using
pxdom.getDOMImplementation('').
"""
[MODE_SYNCHRONOUS,MODE_ASYNCHRONOUS
]=range(1, 3)
_features= {
'xml': ['1.0', '2.0', '3.0'],
'core': ['2.0', '3.0'],
'ls': ['3.0'],
'xmlversion': ['1.0', '1.1']
}
def hasFeature(self, feature, version):
f= string.lower(feature)
if f[:1]=='+':
f= f[1:]
if self._features.has_key(f):
if version in self._features[f]+['', None]:
return True
return False
def getFeature(self, feature, version):
if self.hasFeature(feature, version):
return self
def createDocument(self, namespaceURI, qualifiedName, doctype):
if namespaceURI=='':
namespaceURI= None
document= Document()
if doctype is not None:
document.appendChild(doctype)
if qualifiedName is not None:
root= document.createElementNS(namespaceURI, qualifiedName)
document.appendChild(root)
return document
def createDocumentType(self, qualifiedName, publicId, systemId):
_checkName(qualifiedName)
if _splitName(qualifiedName)[1] is None:
raise NamespaceErr(qualifiedName, None)
doctype= DocumentType(None, qualifiedName, publicId, systemId)
doctype.entities.readonly= True
doctype.notations.readonly= True
return doctype
_implementation= DOMImplementation()
def getDOMImplementation(features= ''):
"""DOM 3 Core hook to get the Implementation object
If features is supplied, only return the implementation if all features are
satisfied.
"""
fv= string.split(features, ' ')
for index in range(0, len(fv)-1, 2):
if not _implementation.hasFeature(fv[index], fv[index+1]):
return None
return _implementation
def getDOMImplementationList(features= ''):
"""DOM 3 Core method to get implementations in a list wrapper
For pxdom this will only ever be the single implementation, if any.
"""
implementation= getDOMImplementation(features)
implementationList= DOMImplementationList()
if implementation is not None:
implementationList._append(implementation)
implementationList.readonly= True
return implementationList
class DOMImplementationList(DOMList):
"""List of DOMImplementation classes
No extra capabilities over DOMList, but is an interface expected by spec.
"""
pass
class DOMConfiguration(DOMObject):
"""Mapping of DOM-related option name strings to values
The 'infoset' and 'canonical-form' parameters map to multiple other
parameters rather than working independently.
Some DOM parameters are optional features that may not be supported
and in this case cannot be set. pxdom adds some extra parameters for
extended pxdom-specific configuration, these are prefixed 'pxdom-'.
"""
_defaults= {
# Core configuration
'canonical-form': (False, True ),
'cdata-sections': (True, True ),
'check-character-normalization': (False, CNORM),
'comments': (True, True ),
'datatype-normalization': (False, False),
'element-content-whitespace': (True, True ),
'entities': (True, True ),
'error-handler': (None, True ),
'ignore-unknown-character-denormalizations': (True, False),
'namespaces': (True, True ),
'namespace-declarations': (True, True ),
'normalize-characters': (False, CNORM),
'schema-location': (None, False),
'schema-type': (None, False),
'split-cdata-sections': (True, True ),
'validate': (False, False),
'validate-if-schema': (False, False),
'well-formed': (True, True ),
# LSParser-specific configuration
'charset-overrides-xml-encoding': (True, True ),
'disallow-doctype': (False, True ),
'resource-resolver': (None, True ),
'supported-media-types-only': (False, True),
# LSSerializer-specific configuration
'discard-default-content': (True, True ),
'format-pretty-print': (False, True ),
'xml-declaration': (True, True ),
# Non-standard extensions
'pxdom-assume-element-content': (False, True ),
'pxdom-resolve-resources': (True, True ),
'pxdom-html-compatible': (False, True ),
# Switches to make required normalizeDocument operations optional
'pxdom-normalize-text': (True, True ),
'pxdom-reset-identity': (True, True ),
'pxdom-update-entities': (True, True ),
'pxdom-preserve-base-uri': (True, True ),
'pxdom-examine-cdata-sections': (True, True ),
# Normally used only inside an entity reference
'pxdom-fix-unbound-namespaces': (False, True )
}
_complexparameters= {
'infoset': ( # mirrors when the following are:
('cdata-sections', 'datatype-normalization', 'entities', 'validate-if-schema'), # True
('comments', 'element-content-whitespace', 'namespace-declarations', 'namespaces', 'well-formed') # False
),
'canonical-form': (
('cdata-sections', 'entities', 'format-pretty-print', 'normalize-characters', 'discard-default-content', 'xml-declaration', 'pxdom-html-compatible'),
('element-content-whitespace', 'namespace-declarations', 'namespaces', 'well-formed')
),
}
def __init__(self, copyFrom= None):
"""Make a new DOMConfiguration mapping
Use either default values, or the current values of another
DOMConfiguration (copy-constructor)
"""
DOMObject.__init__(self)
self._parameters= {}
for (name, (value, canSet)) in self._defaults.items():
if copyFrom is not None:
self._parameters[name]= copyFrom._parameters[name]
else:
self._parameters[name]= value
def canSetParameter(self, name, value):
name= string.lower(name)
if name=='infoset':
return True
if self._parameters[name]==value:
return True
return self._defaults.get(name, (None, False))[1]
def getParameter(self, name):
name= string.lower(name)
if self._complexparameters.has_key(name):
for b in False, True:
for p in self._complexparameters[name][b]:
if self._parameters[p]!=b:
return False
if name=='infoset':
return True
if not self._parameters.has_key(name):
raise NotFoundErr(self, None, name)
return self._parameters[name]
def setParameter(self, name, value):
name= string.lower(name)
if self._complexparameters.has_key(name):
if value:
for b in False, True:
for p in self._complexparameters[name][b]:
self._parameters[p]= b
if name=='infoset':
return
if not self._defaults.has_key(name):
raise NotFoundErr(self, None, name)
if self._parameters[name]!=value:
if not self._defaults[name][1]:
raise NotSupportedErr(self, name)
self._parameters[name]= value
def _get_parameterNames(self):
return DOMList(self._parameters.keys()+['infoset'])
# Convenience method to do character normalization and/or check character
# normalization on a string, depending on the parameters set on the config
#
def _cnorm(self, text, node, isParse= False):
nc= self._parameters['normalize-characters']
cn= self._parameters['check-character-normalization']
if not nc and not cn or text=='' or not isinstance(text, Unicode):
return text
normal= unicodedata.normalize('NFC', text)
if nc:
text= normal
if (not nc and text!=normal or cn and (
unicodedata.combining(text[0])!=0 or text[0] in EXTRACOMPOSERS
)):
self._handleError(CheckNormErr(node, isParse))
return text
# Convenience method for pxdom to callback the error-handler if one is set
# on the DOMConfiguration, and raise an exception if the error or handler
# says processing should not continue.
#
def _handleError(self, error):
handler= self._parameters['error-handler']
cont= None
if handler is not None:
cont= handler.handleError(error)
if not error.allowContinue(cont):
raise error
# LSParsers can't have well-formed set to False, and default entities and
# cdata-sections to False instead of True
#
class ParserConfiguration(DOMConfiguration):
_defaults= dictadd(DOMConfiguration._defaults, {
'well-formed': (True, False),
'entities': (False, True),
'cdata-sections': (False, True)
})
# Predefined configurations for simple normalisation processes outside of the
# normalizeDocument method
#
DOMCONFIG_NONE= DOMConfiguration()
DOMCONFIG_NONE.setParameter('well-formed', False)
DOMCONFIG_NONE.setParameter('namespaces', False)
DOMCONFIG_NONE.setParameter('pxdom-normalize-text', False)
DOMCONFIG_NONE.setParameter('pxdom-update-entities', False)
DOMCONFIG_NONE.setParameter('pxdom-examine-cdata-sections', False)
DOMCONFIG_NONE.setParameter('pxdom-reset-identity', False)
DOMCONFIG_ENTS= DOMConfiguration(DOMCONFIG_NONE)
DOMCONFIG_ENTS.setParameter('pxdom-update-entities', True)
DOMCONFIG_ENTS_BIND= DOMConfiguration(DOMCONFIG_ENTS)
DOMCONFIG_ENTS_BIND.setParameter('pxdom-fix-unbound-namespaces', True)
DOMCONFIG_TEXT= DOMConfiguration(DOMCONFIG_NONE)
DOMCONFIG_TEXT.setParameter('pxdom-normalize-text', True)
if CNORM:
DOMCONFIG_TEXT_CANONICAL= DOMConfiguration(DOMCONFIG_TEXT)
DOMCONFIG_TEXT_CANONICAL.setParameter('normalize-characters', True)
class TypeInfo(DOMObject):
"""Value type giving information about schema type information
Belongs to Element or Attribute. Since only DTD schema information is
supported, this returns nulls except for Attribute typeNames, which might
be grabbable from the doctype's attlists.
"""
[DERIVATION_RESTRICTION, DERIVATION_EXTENSION, DERIVATION_UNION,
DERIVATION_LIST]= map(lambda n: 2**n, range(1, 5))
def __init__(self, ownerNode):
DOMObject.__init__(self, False)
self._ownerNode= ownerNode
def _get_typeNamespace(self):
return self._getType()[0]
def _get_typeName(self):
return self._getType()[1]
def _getType(self):
if self._ownerNode.nodeType==Node.ATTRIBUTE_NODE:
if (
self._ownerNode.ownerElement is not None and
self._ownerNode.ownerDocument is not None and
self._ownerNode.ownerDocument.doctype is not None
):
attlist= self._ownerNode.ownerDocument.doctype._attlists.getNamedItem(self._ownerNode.ownerElement.tagName)
if attlist is not None:
attdecl= attlist.declarations.getNamedItem(self._ownerNode.name)
if attdecl is not None:
return (DTNS, AttributeDeclaration.ATTR_NAMES[attdecl.attributeType])
if (self._ownerNode.name=='xml:id'):
return (DTNS, 'ID')
return (None, None)
def isDerivedFrom(self, typeNamespaceArg, typeNameArg, derivationMethod):
"""DOM 3 required method, otherwise not useful
pxdom does not support XML Schema; for DTD schema this method always
returns false.
"""
return False
class DOMLocator(DOMObject):
"""Value type used to return source document/position information
Used in the standard DOM to locate DOMErrors; pxdom also allows any Node
to be located this way.
"""
def __init__(self, node= None, lineNumber= -1, columnNumber= -1, uri= None):
self._relatedNode= node
self._lineNumber= lineNumber
self._columnNumber= columnNumber
if uri is not None:
self._uri= uri
elif node is not None:
self._uri= node._ownerDocument.documentURI
else:
self._uri= ''
def _get_lineNumber(self):
return self._lineNumber
def _get_columnNumber(self):
return self._columnNumber
def _get_byteOffset(self):
return -1
def _get_utf16Offset(self):
return -1
def _get_relatedNode(self):
return self._relatedNode
def _get_uri(self):
return self._uri
class UserDataHandler:
"""Constants for UserDataHandler classes
Any Python object that supplies a 'handle' method can be bound to the
DOM type UserDataHandler; this merely holds its static constants. NB.
NODE_DELETED is never called because (as noted in the DOM Core spec)
we have no idea when the object will be deleted by Python. No __del__
handler is provided for this because __del__ has negative implications
for garbage collection.
"""
[NODE_CLONED, NODE_IMPORTED, NODE_DELETED, NODE_RENAMED, NODE_ADOPTED
]= range(1, 6)
# Core node classes
# ============================================================================
class Node(DOMObject):
""" Abstract base class for all DOM Nodes.
"""
[ELEMENT_NODE,ATTRIBUTE_NODE,TEXT_NODE,CDATA_SECTION_NODE,
ENTITY_REFERENCE_NODE,ENTITY_NODE,PROCESSING_INSTRUCTION_NODE,COMMENT_NODE,
DOCUMENT_NODE,DOCUMENT_TYPE_NODE,DOCUMENT_FRAGMENT_NODE,NOTATION_NODE
]= range(1,13)
[ELEMENT_DECLARATION_NODE,ATTRIBUTE_DECLARATION_NODE,ATTRIBUTE_LIST_NODE
]= range(301, 304)
[DOCUMENT_POSITION_DISCONNECTED,DOCUMENT_POSITION_PRECEDING,
DOCUMENT_POSITION_FOLLOWING,DOCUMENT_POSITION_CONTAINS,
DOCUMENT_POSITION_CONTAINED_BY,DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
]= map(lambda n: 1<<n, range(6))
# Node properties
#
def __init__(self,
ownerDocument= None, namespaceURI= None, localName= None, prefix= None
):
DOMObject.__init__(self)
self._ownerDocument= ownerDocument
self._containerNode= None
self._namespaceURI= namespaceURI
self._localName= localName
self._prefix= prefix
self._childNodes= ChildNodeList(self)
self._attributes= None
self._userData= {}
self._childNodes.readonly= True
self._sequence= 0
self._row= -1
self._col= -1
def _cloneTo(self, node):
node._ownerDocument= self._ownerDocument
node._namespaceURI= self._namespaceURI
node._localName= self._localName
node._prefix= self._prefix
node._row= self._row
node._col= self._col
def _get_ownerDocument(self): return self._ownerDocument
def _get_parentNode(self): return self._containerNode
def _get_nodeType(self): return None
def _get_nodeName(self): return '#abstract-node'
def _get_nodeValue(self): return None
def _get_namespaceURI(self): return self._namespaceURI
def _get_localName(self): return self._localName
def _get_prefix(self): return self._prefix
def _get_childNodes(self): return self._childNodes
def _get_attributes(self): return self._attributes
def _set_nodeValue(self, value):
pass
def __repr__(self):
t= repr(self.nodeName)
if len(t)>REPR_MAX_LEN:
t= t[:REPR_MAX_LEN-2]+'...'
if t[:1]=='u':
t= t[1:]
return '<pxdom.%s %s>' % (self.__class__.__name__, t)
# Hierarchy access
#
def _get_firstChild(self):
if self.childNodes.length>0:
return self.childNodes.item(0)
return None
def _get_lastChild(self):
if self.childNodes.length>0:
return self._childNodes.item(self.childNodes.length-1)
return None
def _get_previousSibling(self):
if self.parentNode is None:
return None
try:
index= self.parentNode.childNodes._index(self)
except ValueError:
return None
if index<1:
return None
return self.parentNode.childNodes.item(index-1)
def _get_nextSibling(self):
if self.parentNode is None:
return None
try: