-
-
Notifications
You must be signed in to change notification settings - Fork 559
/
apihelpers.pxi
1643 lines (1491 loc) · 55.9 KB
/
apihelpers.pxi
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
# Private/public helper functions for API functions
cimport uri
cdef void displayNode(xmlNode* c_node, indent):
# to help with debugging
cdef xmlNode* c_child
print indent * u' ', <long>c_node
c_child = c_node.children
while c_child is not NULL:
displayNode(c_child, indent + 1)
c_child = c_child.next
cdef inline int _assertValidNode(_Element element) except -1:
assert element._c_node is not NULL, u"invalid Element proxy at %s" % id(element)
cdef inline int _assertValidDoc(_Document doc) except -1:
assert doc._c_doc is not NULL, u"invalid Document proxy at %s" % id(doc)
cdef _Document _documentOrRaise(object input):
u"""Call this to get the document of a _Document, _ElementTree or _Element
object, or to raise an exception if it can't be determined.
Should be used in all API functions for consistency.
"""
cdef _Document doc
if isinstance(input, _ElementTree):
if (<_ElementTree>input)._context_node is not None:
doc = (<_ElementTree>input)._context_node._doc
else:
doc = None
elif isinstance(input, _Element):
doc = (<_Element>input)._doc
elif isinstance(input, _Document):
doc = <_Document>input
else:
raise TypeError, u"Invalid input object: %s" % \
python._fqtypename(input)
if doc is None:
raise ValueError, u"Input object has no document: %s" % \
python._fqtypename(input)
_assertValidDoc(doc)
return doc
cdef _Element _rootNodeOrRaise(object input):
u"""Call this to get the root node of a _Document, _ElementTree or
_Element object, or to raise an exception if it can't be determined.
Should be used in all API functions for consistency.
"""
cdef _Element node
if isinstance(input, _ElementTree):
node = (<_ElementTree>input)._context_node
elif isinstance(input, _Element):
node = <_Element>input
elif isinstance(input, _Document):
node = (<_Document>input).getroot()
else:
raise TypeError, u"Invalid input object: %s" % \
python._fqtypename(input)
if node is None:
raise ValueError, u"Input object has no element: %s" % \
python._fqtypename(input)
_assertValidNode(node)
return node
cdef _Document _documentOf(object input):
# call this to get the document of a
# _Document, _ElementTree or _Element object
# may return None!
cdef _Element element
cdef _Document doc = None
if isinstance(input, _ElementTree):
element = (<_ElementTree>input)._context_node
if element is not None:
doc = element._doc
elif isinstance(input, _Element):
doc = (<_Element>input)._doc
elif isinstance(input, _Document):
doc = <_Document>input
if doc is not None:
_assertValidDoc(doc)
return doc
cdef _Element _rootNodeOf(object input):
# call this to get the root node of a
# _Document, _ElementTree or _Element object
# may return None!
cdef _Element element = None
if isinstance(input, _ElementTree):
element = (<_ElementTree>input)._context_node
elif isinstance(input, _Element):
element = <_Element>input
elif isinstance(input, _Document):
element = (<_Document>input).getroot()
if element is not None:
_assertValidNode(element)
return element
cdef _Element _makeElement(tag, xmlDoc* c_doc, _Document doc,
_BaseParser parser, text, tail, attrib, nsmap,
extra_attrs):
u"""Create a new element and initialize text content, namespaces and
attributes.
This helper function will reuse as much of the existing document as
possible:
If 'parser' is None, the parser will be inherited from 'doc' or the
default parser will be used.
If 'doc' is None, 'c_doc' is used to create a new _Document and the new
element is made its root node.
If 'c_doc' is also NULL, a new xmlDoc will be created.
"""
cdef xmlNode* c_node
if doc is not None:
c_doc = doc._c_doc
ns_utf, name_utf = _getNsTag(tag)
if parser is not None and parser._for_html:
_htmlTagValidOrRaise(name_utf)
if c_doc is NULL:
c_doc = _newHTMLDoc()
else:
_tagValidOrRaise(name_utf)
if c_doc is NULL:
c_doc = _newXMLDoc()
c_node = _createElement(c_doc, name_utf)
if c_node is NULL:
if doc is None and c_doc is not NULL:
tree.xmlFreeDoc(c_doc)
raise MemoryError()
try:
if doc is None:
tree.xmlDocSetRootElement(c_doc, c_node)
doc = _documentFactory(c_doc, parser)
if text is not None:
_setNodeText(c_node, text)
if tail is not None:
_setTailText(c_node, tail)
# add namespaces to node if necessary
_initNodeNamespaces(c_node, doc, ns_utf, nsmap)
_initNodeAttributes(c_node, doc, attrib, extra_attrs)
return _elementFactory(doc, c_node)
except:
# free allocated c_node/c_doc unless Python does it for us
if c_node.doc is not c_doc:
# node not yet in document => will not be freed by document
if tail is not None:
_removeText(c_node.next) # tail
tree.xmlFreeNode(c_node)
if doc is None:
# c_doc will not be freed by doc
tree.xmlFreeDoc(c_doc)
raise
cdef int _initNewElement(_Element element, bint is_html, name_utf, ns_utf,
_BaseParser parser, attrib, nsmap, extra_attrs) except -1:
u"""Initialise a new Element object.
This is used when users instantiate a Python Element class
directly, without it being mapped to an existing XML node.
"""
cdef xmlDoc* c_doc
cdef xmlNode* c_node
cdef _Document doc
if is_html:
_htmlTagValidOrRaise(name_utf)
c_doc = _newHTMLDoc()
else:
_tagValidOrRaise(name_utf)
c_doc = _newXMLDoc()
c_node = _createElement(c_doc, name_utf)
if c_node is NULL:
if c_doc is not NULL:
tree.xmlFreeDoc(c_doc)
raise MemoryError()
tree.xmlDocSetRootElement(c_doc, c_node)
doc = _documentFactory(c_doc, parser)
# add namespaces to node if necessary
_initNodeNamespaces(c_node, doc, ns_utf, nsmap)
_initNodeAttributes(c_node, doc, attrib, extra_attrs)
_registerProxy(element, doc, c_node)
element._init()
return 0
cdef _Element _makeSubElement(_Element parent, tag, text, tail,
attrib, nsmap, extra_attrs):
u"""Create a new child element and initialize text content, namespaces and
attributes.
"""
cdef xmlNode* c_node
cdef xmlDoc* c_doc
if parent is None or parent._doc is None:
return None
_assertValidNode(parent)
ns_utf, name_utf = _getNsTag(tag)
c_doc = parent._doc._c_doc
if parent._doc._parser is not None and parent._doc._parser._for_html:
_htmlTagValidOrRaise(name_utf)
else:
_tagValidOrRaise(name_utf)
c_node = _createElement(c_doc, name_utf)
if c_node is NULL:
raise MemoryError()
tree.xmlAddChild(parent._c_node, c_node)
try:
if text is not None:
_setNodeText(c_node, text)
if tail is not None:
_setTailText(c_node, tail)
# add namespaces to node if necessary
_initNodeNamespaces(c_node, parent._doc, ns_utf, nsmap)
_initNodeAttributes(c_node, parent._doc, attrib, extra_attrs)
return _elementFactory(parent._doc, c_node)
except:
# make sure we clean up in case of an error
_removeNode(parent._doc, c_node)
raise
cdef int _initNodeNamespaces(xmlNode* c_node, _Document doc,
object node_ns_utf, object nsmap) except -1:
u"""Lookup current namespace prefixes, then set namespace structure for
node and register new ns-prefix mappings.
This only works for a newly created node!
"""
cdef xmlNs* c_ns
cdef char* c_prefix
cdef char* c_href
cdef list nsdefs
if not nsmap:
if node_ns_utf is not None:
_uriValidOrRaise(node_ns_utf)
doc._setNodeNs(c_node, _cstr(node_ns_utf))
return 0
nsdefs = list(nsmap.items())
if None in nsmap and len(nsdefs) > 1:
# Move the default namespace to the end. This makes sure libxml2
# prefers a prefix if the ns is defined redundantly on the same
# element. That way, users can work around a problem themselves
# where default namespace attributes on non-default namespaced
# elements serialise without prefix (i.e. into the non-default
# namespace).
item = (None, nsmap[None])
nsdefs.remove(item)
nsdefs.append(item)
for prefix, href in nsdefs:
href_utf = _utf8(href)
_uriValidOrRaise(href_utf)
c_href = _cstr(href_utf)
if prefix is not None:
prefix_utf = _utf8(prefix)
_prefixValidOrRaise(prefix_utf)
c_prefix = _cstr(prefix_utf)
else:
c_prefix = NULL
# add namespace with prefix if it is not already known
c_ns = tree.xmlSearchNs(doc._c_doc, c_node, c_prefix)
if c_ns is NULL or \
c_ns.href is NULL or \
cstring_h.strcmp(c_ns.href, c_href) != 0:
c_ns = tree.xmlNewNs(c_node, c_href, c_prefix)
if href_utf == node_ns_utf:
tree.xmlSetNs(c_node, c_ns)
node_ns_utf = None
if node_ns_utf is not None:
doc._setNodeNs(c_node, _cstr(node_ns_utf))
return 0
cdef _initNodeAttributes(xmlNode* c_node, _Document doc, attrib, extra):
u"""Initialise the attributes of an element node.
"""
cdef bint is_html
cdef xmlNs* c_ns
# 'extra' is not checked here (expected to be a keyword dict)
if attrib is not None and not hasattr(attrib, u'items'):
raise TypeError, u"Invalid attribute dictionary: %s" % \
python._fqtypename(attrib)
if extra is not None and extra:
if attrib is None:
attrib = extra
else:
attrib.update(extra)
if attrib:
is_html = doc._parser._for_html
for name, value in sorted(attrib.items()):
attr_ns_utf, attr_name_utf = _getNsTag(name)
if not is_html:
_attributeValidOrRaise(attr_name_utf)
value_utf = _utf8(value)
if attr_ns_utf is None:
tree.xmlNewProp(c_node, _cstr(attr_name_utf), _cstr(value_utf))
else:
_uriValidOrRaise(attr_ns_utf)
c_ns = doc._findOrBuildNodeNs(c_node, _cstr(attr_ns_utf), NULL, 1)
tree.xmlNewNsProp(c_node, c_ns,
_cstr(attr_name_utf), _cstr(value_utf))
ctypedef struct _ns_node_ref:
xmlNs* ns
xmlNode* node
cdef int _removeUnusedNamespaceDeclarations(xmlNode* c_element) except -1:
u"""Remove any namespace declarations from a subtree that are not used by
any of its elements (or attributes).
"""
cdef _ns_node_ref* c_ns_list
cdef _ns_node_ref* c_nsref_ptr
cdef xmlNs* c_nsdef
cdef xmlNode* c_node
cdef size_t c_ns_list_size
cdef size_t c_ns_list_len
cdef size_t i
c_ns_list = NULL
c_ns_list_size = 0
c_ns_list_len = 0
if c_element.parent is not NULL and \
c_element.parent.type == tree.XML_DOCUMENT_NODE:
# include the document node
c_nsdef = c_element.parent.nsDef
while c_nsdef is not NULL:
if c_ns_list_len >= c_ns_list_size:
if c_ns_list is NULL:
c_ns_list_size = 20
else:
c_ns_list_size *= 2
c_nsref_ptr = <_ns_node_ref*> stdlib.realloc(
c_ns_list, c_ns_list_size * sizeof(_ns_node_ref))
if c_nsref_ptr is NULL:
if c_ns_list is not NULL:
stdlib.free(c_ns_list)
raise MemoryError()
c_ns_list = c_nsref_ptr
c_ns_list[c_ns_list_len].ns = c_nsdef
c_ns_list[c_ns_list_len].node = c_element.parent
c_ns_list_len += 1
c_nsdef = c_nsdef.next
tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_element, c_element, 1)
# collect all new namespace declarations into the ns list
c_nsdef = c_element.nsDef
while c_nsdef is not NULL:
if c_ns_list_len >= c_ns_list_size:
if c_ns_list is NULL:
c_ns_list_size = 20
else:
c_ns_list_size *= 2
c_nsref_ptr = <_ns_node_ref*> stdlib.realloc(
c_ns_list, c_ns_list_size * sizeof(_ns_node_ref))
if c_nsref_ptr is NULL:
if c_ns_list is not NULL:
stdlib.free(c_ns_list)
raise MemoryError()
c_ns_list = c_nsref_ptr
c_ns_list[c_ns_list_len].ns = c_nsdef
c_ns_list[c_ns_list_len].node = c_element
c_ns_list_len += 1
c_nsdef = c_nsdef.next
# remove all namespace declarations from the list that are referenced
if c_element.type == tree.XML_ELEMENT_NODE:
c_node = c_element
while c_node is not NULL:
if c_node.ns is not NULL:
for i in range(c_ns_list_len):
if c_node.ns is c_ns_list[i].ns:
c_ns_list_len -= 1
c_ns_list[i].ns = c_ns_list[c_ns_list_len].ns
c_ns_list[i].node = c_ns_list[c_ns_list_len].node
c_ns_list[c_ns_list_len].ns = NULL
c_ns_list[c_ns_list_len].node = NULL
break
if c_node is c_element:
# continue with attributes
c_node = <xmlNode*>c_element.properties
else:
c_node = c_node.next
tree.END_FOR_EACH_ELEMENT_FROM(c_element)
if c_ns_list is NULL:
return 0
# free all namespace declarations that remained in the list
for i in range(c_ns_list_len):
c_node = c_ns_list[i].node
c_nsdef = c_node.nsDef
if c_nsdef is c_ns_list[i].ns:
c_node.nsDef = c_node.nsDef.next
else:
while c_nsdef.next is not c_ns_list[i].ns:
c_nsdef = c_nsdef.next
c_nsdef.next = c_nsdef.next.next
tree.xmlFreeNs(c_ns_list[i].ns)
if c_ns_list is not NULL:
stdlib.free(c_ns_list)
return 0
cdef xmlNs* _searchNsByHref(xmlNode* c_node, char* c_href, bint is_attribute):
u"""Search a namespace declaration that covers a node (element or
attribute).
For attributes, try to find a prefixed namespace declaration
instead of the default namespaces. This helps in supporting
round-trips for attributes on elements with a different namespace.
"""
cdef xmlNs* c_ns
cdef xmlNs* c_default_ns = NULL
cdef xmlNode* c_element
if c_href is NULL or c_node is NULL or c_node.type == tree.XML_ENTITY_REF_NODE:
return NULL
if cstring_h.strcmp(c_href, tree.XML_XML_NAMESPACE) == 0:
# no special cases here, let libxml2 handle this
return tree.xmlSearchNsByHref(c_node.doc, c_node, c_href)
if c_node.type == tree.XML_ATTRIBUTE_NODE:
is_attribute = 1
while c_node is not NULL and c_node.type != tree.XML_ELEMENT_NODE:
c_node = c_node.parent
c_element = c_node
while c_node is not NULL:
if c_node.type == tree.XML_ELEMENT_NODE:
c_ns = c_node.nsDef
while c_ns is not NULL:
if c_ns.href is not NULL and cstring_h.strcmp(c_href, c_ns.href) == 0:
if c_ns.prefix is NULL and is_attribute:
# for attributes, continue searching a named
# prefix, but keep the first default namespace
# declaration that we found
if c_default_ns is NULL:
c_default_ns = c_ns
elif tree.xmlSearchNs(
c_element.doc, c_element, c_ns.prefix) is c_ns:
# start node is in namespace scope => found!
return c_ns
c_ns = c_ns.next
if c_node is not c_element and c_node.ns is not NULL:
# optimise: the node may have the namespace itself
c_ns = c_node.ns
if c_ns.href is not NULL and cstring_h.strcmp(c_href, c_ns.href) == 0:
if c_ns.prefix is NULL and is_attribute:
# for attributes, continue searching a named
# prefix, but keep the first default namespace
# declaration that we found
if c_default_ns is NULL:
c_default_ns = c_ns
elif tree.xmlSearchNs(
c_element.doc, c_element, c_ns.prefix) is c_ns:
# start node is in namespace scope => found!
return c_ns
c_node = c_node.parent
# nothing found => use a matching default namespace or fail
if c_default_ns is not NULL:
if tree.xmlSearchNs(c_element.doc, c_element, NULL) is c_default_ns:
return c_default_ns
return NULL
cdef int _replaceNodeByChildren(_Document doc, xmlNode* c_node) except -1:
# NOTE: this does not deallocate the node, just unlink it!
cdef xmlNode* c_parent
cdef xmlNode* c_child
if c_node.children is NULL:
tree.xmlUnlinkNode(c_node)
return 0
c_parent = c_node.parent
# fix parent links of children
c_child = c_node.children
while c_child is not NULL:
c_child.parent = c_parent
c_child = c_child.next
# fix namespace references of children if their parent's namespace
# declarations get lost
if c_node.nsDef is not NULL:
c_child = c_node.children
while c_child is not NULL:
moveNodeToDocument(doc, doc._c_doc, c_child)
c_child = c_child.next
# fix sibling links to/from child slice
if c_node.prev is NULL:
c_parent.children = c_node.children
else:
c_node.prev.next = c_node.children
c_node.children.prev = c_node.prev
if c_node.next is NULL:
c_parent.last = c_node.last
else:
c_node.next.prev = c_node.last
c_node.last.next = c_node.next
# unlink c_node
c_node.children = c_node.last = NULL
c_node.parent = c_node.next = c_node.prev = NULL
return 0
cdef object _attributeValue(xmlNode* c_element, xmlAttr* c_attrib_node):
cdef char* value
cdef char* c_href
c_href = _getNs(<xmlNode*>c_attrib_node)
value = tree.xmlGetNsProp(c_element, c_attrib_node.name, c_href)
try:
result = funicode(value)
finally:
tree.xmlFree(value)
return result
cdef object _attributeValueFromNsName(xmlNode* c_element,
char* c_href, char* c_name):
cdef char* c_result = tree.xmlGetNsProp(c_element, c_name, c_href)
if c_result is NULL:
return None
try:
result = funicode(c_result)
finally:
tree.xmlFree(c_result)
return result
cdef object _getNodeAttributeValue(xmlNode* c_node, key, default):
cdef char* c_result
cdef char* c_href
ns, tag = _getNsTag(key)
c_href = NULL if ns is None else _cstr(ns)
c_result = tree.xmlGetNsProp(c_node, _cstr(tag), c_href)
if c_result is NULL:
# XXX free namespace that is not in use..?
return default
try:
result = funicode(c_result)
finally:
tree.xmlFree(c_result)
return result
cdef inline object _getAttributeValue(_Element element, key, default):
return _getNodeAttributeValue(element._c_node, key, default)
cdef int _setAttributeValue(_Element element, key, value) except -1:
cdef xmlNs* c_ns
cdef char* c_value
cdef char* c_tag
ns, tag = _getNsTag(key)
if not element._doc._parser._for_html:
_attributeValidOrRaise(tag)
c_tag = _cstr(tag)
if isinstance(value, QName):
value = _resolveQNameText(element, value)
else:
value = _utf8(value)
c_value = _cstr(value)
if ns is None:
c_ns = NULL
else:
c_ns = element._doc._findOrBuildNodeNs(element._c_node,
_cstr(ns), NULL, 1)
tree.xmlSetNsProp(element._c_node, c_ns, c_tag, c_value)
return 0
cdef int _delAttribute(_Element element, key) except -1:
cdef char* c_href
ns, tag = _getNsTag(key)
c_href = NULL if ns is None else _cstr(ns)
if _delAttributeFromNsName(element._c_node, c_href, _cstr(tag)):
raise KeyError, key
return 0
cdef int _delAttributeFromNsName(xmlNode* c_node, char* c_href, char* c_name):
cdef xmlAttr* c_attr
c_attr = tree.xmlHasNsProp(c_node, c_name, c_href)
if c_attr is NULL:
# XXX free namespace that is not in use..?
return -1
tree.xmlRemoveProp(c_attr)
return 0
cdef list _collectAttributes(xmlNode* c_node, int collecttype):
u"""Collect all attributes of a node in a list. Depending on collecttype,
it collects either the name (1), the value (2) or the name-value tuples.
"""
cdef Py_ssize_t count
cdef xmlAttr* c_attr
c_attr = c_node.properties
count = 0
while c_attr is not NULL:
if c_attr.type == tree.XML_ATTRIBUTE_NODE:
count = count + 1
c_attr = c_attr.next
if count == 0:
return []
attributes = python.PyList_New(count)
c_attr = c_node.properties
count = 0
while c_attr is not NULL:
if c_attr.type == tree.XML_ATTRIBUTE_NODE:
if collecttype == 1:
item = _namespacedName(<xmlNode*>c_attr)
elif collecttype == 2:
item = _attributeValue(c_node, c_attr)
else:
item = (_namespacedName(<xmlNode*>c_attr),
_attributeValue(c_node, c_attr))
python.Py_INCREF(item)
python.PyList_SET_ITEM(attributes, count, item)
count = count + 1
c_attr = c_attr.next
return attributes
cdef object __RE_XML_ENCODING
__RE_XML_ENCODING = re.compile(
ur'^(\s*<\?\s*xml[^>]+)\s+encoding\s*=\s*["\'][^"\']*["\']\s*', re.U)
cdef object __REPLACE_XML_ENCODING
__REPLACE_XML_ENCODING = __RE_XML_ENCODING.sub
cdef object __HAS_XML_ENCODING
__HAS_XML_ENCODING = __RE_XML_ENCODING.match
cdef object _stripEncodingDeclaration(object xml_string):
# this is a hack to remove the XML encoding declaration from unicode
return __REPLACE_XML_ENCODING(ur'\g<1>', xml_string)
cdef bint _hasEncodingDeclaration(object xml_string):
# check if a (unicode) string has an XML encoding declaration
return __HAS_XML_ENCODING(xml_string) is not None
cdef object _stripDeclaration(object xml_string):
# this is a hack to remove the XML declaration when we encode to UTF-8
xml_string = xml_string.strip()
if xml_string[:5] == '<?xml':
i = xml_string.find('?>')
if i != -1:
i = i + 2
while xml_string[i:i+1] in '\n\r ':
i = i+1
xml_string = xml_string[i:]
return xml_string
cdef inline bint _hasText(xmlNode* c_node):
return c_node is not NULL and _textNodeOrSkip(c_node.children) is not NULL
cdef inline bint _hasTail(xmlNode* c_node):
return c_node is not NULL and _textNodeOrSkip(c_node.next) is not NULL
cdef _collectText(xmlNode* c_node):
u"""Collect all text nodes and return them as a unicode string.
Start collecting at c_node.
If there was no text to collect, return None
"""
cdef Py_ssize_t scount
cdef char* c_text
cdef xmlNode* c_node_cur
# check for multiple text nodes
scount = 0
c_text = NULL
c_node_cur = c_node = _textNodeOrSkip(c_node)
while c_node_cur is not NULL:
if c_node_cur.content[0] != c'\0':
c_text = c_node_cur.content
scount += 1
c_node_cur = _textNodeOrSkip(c_node_cur.next)
# handle two most common cases first
if c_text is NULL:
return '' if scount > 0 else None
if scount == 1:
return funicode(c_text)
# the rest is not performance critical anymore
result = b''
while c_node is not NULL:
result = result + c_node.content
c_node = _textNodeOrSkip(c_node.next)
return funicode(result)
cdef void _removeText(xmlNode* c_node):
u"""Remove all text nodes.
Start removing at c_node.
"""
cdef xmlNode* c_next
c_node = _textNodeOrSkip(c_node)
while c_node is not NULL:
c_next = _textNodeOrSkip(c_node.next)
tree.xmlUnlinkNode(c_node)
tree.xmlFreeNode(c_node)
c_node = c_next
cdef int _setNodeText(xmlNode* c_node, value) except -1:
cdef xmlNode* c_text_node
# remove all text nodes at the start first
_removeText(c_node.children)
if value is None:
return 0
# now add new text node with value at start
if python._isString(value):
text = _utf8(value)
c_text_node = tree.xmlNewDocText(c_node.doc, _cstr(text))
elif isinstance(value, CDATA):
c_text_node = tree.xmlNewCDataBlock(
c_node.doc, _cstr((<CDATA>value)._utf8_data),
python.PyBytes_GET_SIZE((<CDATA>value)._utf8_data))
else:
# this will raise the right error
_utf8(value)
return -1
if c_node.children is NULL:
tree.xmlAddChild(c_node, c_text_node)
else:
tree.xmlAddPrevSibling(c_node.children, c_text_node)
return 0
cdef int _setTailText(xmlNode* c_node, value) except -1:
cdef xmlNode* c_text_node
# remove all text nodes at the start first
_removeText(c_node.next)
if value is None:
return 0
text = _utf8(value)
c_text_node = tree.xmlNewDocText(c_node.doc, _cstr(text))
# XXX what if we're the top element?
tree.xmlAddNextSibling(c_node, c_text_node)
return 0
cdef bytes _resolveQNameText(_Element element, value):
cdef xmlNs* c_ns
ns, tag = _getNsTag(value)
if ns is None:
return tag
else:
c_ns = element._doc._findOrBuildNodeNs(
element._c_node, _cstr(ns), NULL, 0)
return python.PyBytes_FromFormat('%s:%s', c_ns.prefix, _cstr(tag))
cdef inline bint _hasChild(xmlNode* c_node):
return c_node is not NULL and _findChildForwards(c_node, 0) is not NULL
cdef inline Py_ssize_t _countElements(xmlNode* c_node):
u"Counts the elements within the following siblings and the node itself."
cdef Py_ssize_t count
count = 0
while c_node is not NULL:
if _isElement(c_node):
count = count + 1
c_node = c_node.next
return count
cdef int _findChildSlice(
slice sliceobject, xmlNode* c_parent,
xmlNode** c_start_node, Py_ssize_t* c_step, Py_ssize_t* c_length) except -1:
u"""Resolve a children slice.
Returns the start node, step size and the slice length in the
pointer arguments.
"""
cdef Py_ssize_t start = 0, stop = 0, childcount
childcount = _countElements(c_parent.children)
if childcount == 0:
c_start_node[0] = NULL
c_length[0] = 0
if sliceobject.step is None:
c_step[0] = 1
else:
python._PyEval_SliceIndex(sliceobject.step, c_step)
return 0
python.PySlice_GetIndicesEx(
sliceobject, childcount, &start, &stop, c_step, c_length)
if start > childcount / 2:
c_start_node[0] = _findChildBackwards(c_parent, childcount - start - 1)
else:
c_start_node[0] = _findChild(c_parent, start)
return 0
cdef bint _isFullSlice(slice sliceobject):
u"""Conservative guess if this slice is a full slice as in ``s[:]``.
"""
cdef Py_ssize_t step = 0
if sliceobject is None:
return 0
if sliceobject.start is None and \
sliceobject.stop is None:
if sliceobject.step is None:
return 1
python._PyEval_SliceIndex(sliceobject.step, &step)
if step == 1:
return 1
return 0
return 0
cdef _collectChildren(_Element element):
cdef xmlNode* c_node
cdef list result = []
c_node = element._c_node.children
if c_node is not NULL:
if not _isElement(c_node):
c_node = _nextElement(c_node)
while c_node is not NULL:
result.append(_elementFactory(element._doc, c_node))
c_node = _nextElement(c_node)
return result
cdef inline xmlNode* _findChild(xmlNode* c_node, Py_ssize_t index):
if index < 0:
return _findChildBackwards(c_node, -index - 1)
else:
return _findChildForwards(c_node, index)
cdef inline xmlNode* _findChildForwards(xmlNode* c_node, Py_ssize_t index):
u"""Return child element of c_node with index, or return NULL if not found.
"""
cdef xmlNode* c_child
cdef Py_ssize_t c
c_child = c_node.children
c = 0
while c_child is not NULL:
if _isElement(c_child):
if c == index:
return c_child
c += 1
c_child = c_child.next
return NULL
cdef inline xmlNode* _findChildBackwards(xmlNode* c_node, Py_ssize_t index):
u"""Return child element of c_node with index, or return NULL if not found.
Search from the end.
"""
cdef xmlNode* c_child
cdef Py_ssize_t c
c_child = c_node.last
c = 0
while c_child is not NULL:
if _isElement(c_child):
if c == index:
return c_child
c += 1
c_child = c_child.prev
return NULL
cdef inline xmlNode* _textNodeOrSkip(xmlNode* c_node) nogil:
u"""Return the node if it's a text node. Skip over ignorable nodes in a
series of text nodes. Return NULL if a non-ignorable node is found.
This is used to skip over XInclude nodes when collecting adjacent text
nodes.
"""
while c_node is not NULL:
if c_node.type == tree.XML_TEXT_NODE or \
c_node.type == tree.XML_CDATA_SECTION_NODE:
return c_node
elif c_node.type == tree.XML_XINCLUDE_START or \
c_node.type == tree.XML_XINCLUDE_END:
c_node = c_node.next
else:
return NULL
return NULL
cdef inline xmlNode* _nextElement(xmlNode* c_node):
u"""Given a node, find the next sibling that is an element.
"""
if c_node is NULL:
return NULL
c_node = c_node.next
while c_node is not NULL:
if _isElement(c_node):
return c_node
c_node = c_node.next
return NULL
cdef inline xmlNode* _previousElement(xmlNode* c_node):
u"""Given a node, find the next sibling that is an element.
"""
if c_node is NULL:
return NULL
c_node = c_node.prev
while c_node is not NULL:
if _isElement(c_node):
return c_node
c_node = c_node.prev
return NULL
cdef inline xmlNode* _parentElement(xmlNode* c_node):
u"Given a node, find the parent element."
if c_node is NULL or not _isElement(c_node):
return NULL
c_node = c_node.parent
if c_node is NULL or not _isElement(c_node):
return NULL
return c_node
cdef inline bint _tagMatches(xmlNode* c_node, char* c_href, char* c_name):
u"""Tests if the node matches namespace URI and tag name.
A node matches if it matches both c_href and c_name.
A node matches c_href if any of the following is true:
* c_href is NULL
* its namespace is NULL and c_href is the empty string
* its namespace string equals the c_href string
A node matches c_name if any of the following is true:
* c_name is NULL
* its name string equals the c_name string
"""
cdef char* c_node_href
if c_node is NULL:
return 0
if c_node.type != tree.XML_ELEMENT_NODE:
# not an element, only succeed if we match everything
return c_name is NULL and c_href is NULL
if c_name is NULL:
if c_href is NULL:
# always match
return 1
else:
c_node_href = _getNs(c_node)
if c_node_href is NULL:
return c_href[0] == c'\0'
else:
return cstring_h.strcmp(c_node_href, c_href) == 0
elif c_href is NULL:
if _getNs(c_node) is not NULL:
return 0
return c_node.name == c_name or cstring_h.strcmp(c_node.name, c_name) == 0
elif c_node.name == c_name or cstring_h.strcmp(c_node.name, c_name) == 0:
c_node_href = _getNs(c_node)
if c_node_href is NULL:
return c_href[0] == c'\0'
else:
return cstring_h.strcmp(c_node_href, c_href) == 0
else:
return 0
cdef inline bint _tagMatchesExactly(xmlNode* c_node, qname* c_qname):
u"""Tests if the node matches namespace URI and tag name.
This differs from _tagMatches() in that it does not consider a
NULL value in qname.href a wildcard, and that it expects the c_name
to be taken from the doc dict, i.e. it only compares the names by
address.
A node matches if it matches both href and c_name of the qname.
A node matches c_href if any of the following is true:
* its namespace is NULL and c_href is the empty string
* its namespace string equals the c_href string
A node matches c_name if any of the following is true:
* c_name is NULL
* its name string points to the same address (!) as c_name
"""
cdef char* c_node_href
if c_qname.c_name is not NULL and c_qname.c_name is not c_node.name:
return 0
c_node_href = _getNs(c_node)
if c_qname.href is NULL:
return c_node_href is NULL or c_node_href[0] == '\0'
elif c_node_href is NULL:
return 0
else:
return cstring_h.strcmp(python.__cstr(c_qname.href), c_node_href) == 0
cdef Py_ssize_t _mapTagsToQnameMatchArray(xmlDoc* c_doc, list ns_tags,
qname* c_ns_tags, bint force_into_dict) except -1:
u"""Map a sequence of (name, namespace) pairs to a qname array for efficient
matching with _tagMatchesExactly() above.
Note that each qname struct in the array owns its href byte string object
if it is not NULL.
"""
cdef Py_ssize_t count = 0
cdef char* c_tag
cdef bytes ns, tag
for ns, tag in ns_tags:
if tag is None:
c_tag = NULL
elif force_into_dict:
c_tag = tree.xmlDictLookup(c_doc.dict, _cstr(tag), len(tag))
if c_tag is NULL:
raise MemoryError()
else:
c_tag = tree.xmlDictExists(c_doc.dict, _cstr(tag), len(tag))
if c_tag is NULL:
# not in the dict => not in the document
continue