summaryrefslogtreecommitdiff
path: root/src/lxml/lxml.etree.pyx
blob: c336cef2317e657b0c802edce360f87d2d3c400c (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
# cython: binding=True

"""
The ``lxml.etree`` module implements the extended ElementTree API for XML.
"""

from __future__ import absolute_import

__docformat__ = u"restructuredtext en"

__all__ = [
    'AttributeBasedElementClassLookup', 'C14NError', 'CDATA',
    'Comment', 'CommentBase', 'CustomElementClassLookup', 'DEBUG',
    'DTD', 'DTDError', 'DTDParseError', 'DTDValidateError',
    'DocumentInvalid', 'ETCompatXMLParser', 'ETXPath', 'Element',
    'ElementBase', 'ElementClassLookup', 'ElementDefaultClassLookup',
    'ElementNamespaceClassLookup', 'ElementTree', 'Entity', 'EntityBase',
    'Error', 'ErrorDomains', 'ErrorLevels', 'ErrorTypes', 'Extension',
    'FallbackElementClassLookup', 'FunctionNamespace', 'HTML',
    'HTMLParser', 'LIBXML_COMPILED_VERSION', 'LIBXML_VERSION',
    'LIBXSLT_COMPILED_VERSION', 'LIBXSLT_VERSION', 'LXML_VERSION',
    'LxmlError', 'LxmlRegistryError', 'LxmlSyntaxError',
    'NamespaceRegistryError', 'PI', 'PIBase', 'ParseError',
    'ParserBasedElementClassLookup', 'ParserError', 'ProcessingInstruction',
    'PyErrorLog', 'PythonElementClassLookup', 'QName', 'RelaxNG',
    'RelaxNGError', 'RelaxNGErrorTypes', 'RelaxNGParseError',
    'RelaxNGValidateError', 'Resolver', 'Schematron', 'SchematronError',
    'SchematronParseError', 'SchematronValidateError', 'SerialisationError',
    'SubElement', 'TreeBuilder', 'XInclude', 'XIncludeError', 'XML',
    'XMLDTDID', 'XMLID', 'XMLParser', 'XMLSchema', 'XMLSchemaError',
    'XMLSchemaParseError', 'XMLSchemaValidateError', 'XMLSyntaxError',
    'XMLTreeBuilder', 'XPath', 'XPathDocumentEvaluator', 'XPathError',
    'XPathEvalError', 'XPathEvaluator', 'XPathFunctionError', 'XPathResultError',
    'XPathSyntaxError', 'XSLT', 'XSLTAccessControl', 'XSLTApplyError',
    'XSLTError', 'XSLTExtension', 'XSLTExtensionError', 'XSLTParseError',
    'XSLTSaveError', 'cleanup_namespaces', 'clear_error_log', 'dump',
    'fromstring', 'fromstringlist', 'get_default_parser', 'iselement',
    'iterparse', 'iterwalk', 'parse', 'parseid', 'register_namespace',
    'set_default_parser', 'set_element_class_lookup', 'strip_attributes',
    'strip_elements', 'strip_tags', 'tostring', 'tostringlist', 'tounicode',
    'use_global_python_log'
    ]

cimport cython

from lxml cimport python
from lxml.includes cimport tree, config
from lxml.includes.tree cimport xmlDoc, xmlNode, xmlAttr, xmlNs, _isElement, _getNs
from lxml.includes.tree cimport const_xmlChar, xmlChar, _xcstr
from lxml.python cimport _cstr, _isString
from lxml.includes cimport xpath
from lxml.includes cimport c14n

# Cython's standard declarations
cimport cpython.mem
cimport cpython.ref
from libc cimport limits, stdio, stdlib
from libc cimport string as cstring_h   # not to be confused with stdlib 'string'
from libc.string cimport const_char

try:
    import __builtin__
except ImportError:
    # Python 3
    import builtins as __builtin__

cdef object _unicode
try:
    _unicode = __builtin__.unicode
except AttributeError:
    # Python 3
    _unicode = __builtin__.str

del __builtin__

cdef object os_path_abspath
from os.path import abspath as os_path_abspath

cdef object BytesIO, StringIO
try:
    from io import BytesIO, StringIO
except (ImportError, AttributeError):
    from StringIO import StringIO, StringIO as BytesIO

cdef object OrderedDict = None
try:
    from collections import OrderedDict
except ImportError:
    pass

cdef object _elementpath
from lxml import _elementpath

cdef object sys
import sys

cdef object re
import re

cdef object islice
from itertools import islice

cdef object ITER_EMPTY = iter(())

try:
    from collections.abc import MutableMapping  # Py3.3+
except ImportError:
    from collections import MutableMapping  # Py2.6+

class _ImmutableMapping(MutableMapping):
    def __getitem__(self, key):
        raise KeyError, key

    def __setitem__(self, key, value):
        raise KeyError, key

    def __delitem__(self, key):
        raise KeyError, key

    def __contains__(self, key):
        return False

    def __len__(self):
        return 0

    def __iter__(self):
        return ITER_EMPTY
    iterkeys = itervalues = iteritems = __iter__

cdef object IMMUTABLE_EMPTY_MAPPING = _ImmutableMapping()
del MutableMapping, _ImmutableMapping


# the rules
# ---------
# any libxml C argument/variable is prefixed with c_
# any non-public function/class is prefixed with an underscore
# instance creation is always through factories

# what to do with libxml2/libxslt error messages?
# 0 : drop
# 1 : use log
DEF __DEBUG = 1

# maximum number of lines in the libxml2/xslt log if __DEBUG == 1
DEF __MAX_LOG_SIZE = 100

# make the compiled-in debug state publicly available
DEBUG = __DEBUG

# A struct to store a cached qualified tag name+href pair.
# While we can borrow the c_name from the document dict,
# PyPy requires us to store a Python reference for the
# namespace in order to keep the byte buffer alive.
cdef struct qname:
    const_xmlChar* c_name
    python.PyObject* href

# global per-thread setup
tree.xmlThrDefIndentTreeOutput(1)
tree.xmlThrDefLineNumbersDefaultValue(1)

_initThreadLogging()

# initialize parser (and threading)
xmlparser.xmlInitParser()

# filename encoding
cdef bytes _FILENAME_ENCODING = (sys.getfilesystemencoding() or sys.getdefaultencoding() or 'ascii').encode("UTF-8")
cdef char* _C_FILENAME_ENCODING = _cstr(_FILENAME_ENCODING)

# set up some default namespace prefixes
cdef dict _DEFAULT_NAMESPACE_PREFIXES = {
    b"http://www.w3.org/XML/1998/namespace": b'xml',
    b"http://www.w3.org/1999/xhtml": b"html",
    b"http://www.w3.org/1999/XSL/Transform": b"xsl",
    b"http://www.w3.org/1999/02/22-rdf-syntax-ns#": b"rdf",
    b"http://schemas.xmlsoap.org/wsdl/": b"wsdl",
    # xml schema
    b"http://www.w3.org/2001/XMLSchema": b"xs",
    b"http://www.w3.org/2001/XMLSchema-instance": b"xsi",
    # dublin core
    b"http://purl.org/dc/elements/1.1/": b"dc",
    # objectify
    b"http://codespeak.net/lxml/objectify/pytype" : b"py",
}

cdef object _check_internal_prefix = re.compile(b"ns\d+$").match

def register_namespace(prefix, uri):
    u"""Registers a namespace prefix that newly created Elements in that
    namespace will use.  The registry is global, and any existing
    mapping for either the given prefix or the namespace URI will be
    removed.
    """
    prefix_utf, uri_utf = _utf8(prefix), _utf8(uri)
    if _check_internal_prefix(prefix_utf):
        raise ValueError("Prefix format reserved for internal use")
    _tagValidOrRaise(prefix_utf)
    _uriValidOrRaise(uri_utf)
    for k, v in list(_DEFAULT_NAMESPACE_PREFIXES.items()):
        if k == uri_utf or v == prefix_utf:
            del _DEFAULT_NAMESPACE_PREFIXES[k]
    _DEFAULT_NAMESPACE_PREFIXES[uri_utf] = prefix_utf


# Error superclass for ElementTree compatibility
class Error(Exception):
    pass

# module level superclass for all exceptions
class LxmlError(Error):
    u"""Main exception base class for lxml.  All other exceptions inherit from
    this one.
    """
    def __init__(self, message, error_log=None):
        super(_Error, self).__init__(message)
        if error_log is None:
            self.error_log = __copyGlobalErrorLog()
        else:
            self.error_log = error_log.copy()

cdef object _Error = Error


# superclass for all syntax errors
class LxmlSyntaxError(LxmlError, SyntaxError):
    u"""Base class for all syntax errors.
    """
    pass

class C14NError(LxmlError):
    u"""Error during C14N serialisation.
    """
    pass

# version information
cdef __unpackDottedVersion(version):
    version_list = []
    l = (version.decode("ascii").replace(u'-', u'.').split(u'.') + [0]*4)[:4]
    for item in l:
        try:
            item = int(item)
        except ValueError:
            if item.startswith(u'dev'):
                count = item[3:]
                item = -300
            elif item.startswith(u'alpha'):
                count = item[5:]
                item = -200
            elif item.startswith(u'beta'):
                count = item[4:]
                item = -100
            else:
                count = 0
            if count:
                item += int(count)
        version_list.append(item)
    return tuple(version_list)

cdef __unpackIntVersion(int c_version):
    return (
        ((c_version / (100*100)) % 100),
        ((c_version / 100)       % 100),
        (c_version               % 100)
        )

cdef int _LIBXML_VERSION_INT
try:
    _LIBXML_VERSION_INT = int(
        re.match(u'[0-9]+', (<unsigned char*>tree.xmlParserVersion).decode("ascii")).group(0))
except Exception:
    print u"Unknown libxml2 version: %s" % (<unsigned char*>tree.xmlParserVersion).decode("latin1")
    _LIBXML_VERSION_INT = 0

LIBXML_VERSION = __unpackIntVersion(_LIBXML_VERSION_INT)
LIBXML_COMPILED_VERSION = __unpackIntVersion(tree.LIBXML_VERSION)
LXML_VERSION = __unpackDottedVersion(tree.LXML_VERSION_STRING)

__version__ = tree.LXML_VERSION_STRING.decode("ascii")


# class for temporary storage of Python references,
# used e.g. for XPath results
@cython.final
@cython.internal
cdef class _TempStore:
    cdef list _storage
    def __init__(self):
        self._storage = []

    cdef int add(self, obj) except -1:
        self._storage.append(obj)
        return 0

    cdef int clear(self) except -1:
        del self._storage[:]
        return 0

# class for temporarily storing exceptions raised in extensions
@cython.internal
cdef class _ExceptionContext:
    cdef object _exc_info
    cdef void clear(self):
        self._exc_info = None

    cdef void _store_raised(self):
        self._exc_info = sys.exc_info()

    cdef void _store_exception(self, exception):
        self._exc_info = (exception, None, None)

    cdef bint _has_raised(self):
        return self._exc_info is not None

    cdef int _raise_if_stored(self) except -1:
        if self._exc_info is None:
            return 0
        type, value, traceback = self._exc_info
        self._exc_info = None
        if value is None and traceback is None:
            raise type
        else:
            raise type, value, traceback


# type of a function that steps from node to node
ctypedef public xmlNode* (*_node_to_node_function)(xmlNode*)


################################################################################
# Include submodules

include "proxy.pxi"        # Proxy handling (element backpointers/memory/etc.)
include "apihelpers.pxi"   # Private helper functions
include "xmlerror.pxi"     # Error and log handling


################################################################################
# Public Python API

@cython.final
@cython.freelist(8)
cdef public class _Document [ type LxmlDocumentType, object LxmlDocument ]:
    u"""Internal base class to reference a libxml document.

    When instances of this class are garbage collected, the libxml
    document is cleaned up.
    """
    cdef int _ns_counter
    cdef bytes _prefix_tail
    cdef xmlDoc* _c_doc
    cdef _BaseParser _parser

    def __dealloc__(self):
        # if there are no more references to the document, it is safe
        # to clean the whole thing up, as all nodes have a reference to
        # the document
        tree.xmlFreeDoc(self._c_doc)

    @cython.final
    cdef getroot(self):
        # return an element proxy for the document root
        cdef xmlNode* c_node
        c_node = tree.xmlDocGetRootElement(self._c_doc)
        if c_node is NULL:
            return None
        return _elementFactory(self, c_node)

    @cython.final
    cdef bint hasdoctype(self):
        # DOCTYPE gets parsed into internal subset (xmlDTD*)
        return self._c_doc is not NULL and self._c_doc.intSubset is not NULL

    @cython.final
    cdef getdoctype(self):
        # get doctype info: root tag, public/system ID (or None if not known)
        cdef tree.xmlDtd* c_dtd
        cdef xmlNode* c_root_node
        public_id = None
        sys_url   = None
        c_dtd = self._c_doc.intSubset
        if c_dtd is not NULL:
            if c_dtd.ExternalID is not NULL:
                public_id = funicode(c_dtd.ExternalID)
            if c_dtd.SystemID is not NULL:
                sys_url = funicode(c_dtd.SystemID)
        c_dtd = self._c_doc.extSubset
        if c_dtd is not NULL:
            if not public_id and c_dtd.ExternalID is not NULL:
                public_id = funicode(c_dtd.ExternalID)
            if not sys_url and c_dtd.SystemID is not NULL:
                sys_url = funicode(c_dtd.SystemID)
        c_root_node = tree.xmlDocGetRootElement(self._c_doc)
        if c_root_node is NULL:
            root_name = None
        else:
            root_name = funicode(c_root_node.name)
        return (root_name, public_id, sys_url)

    @cython.final
    cdef getxmlinfo(self):
        # return XML version and encoding (or None if not known)
        cdef xmlDoc* c_doc = self._c_doc
        if c_doc.version is NULL:
            version = None
        else:
            version = funicode(c_doc.version)
        if c_doc.encoding is NULL:
            encoding = None
        else:
            encoding = funicode(c_doc.encoding)
        return (version, encoding)

    @cython.final
    cdef isstandalone(self):
        # returns True for "standalone=true",
        # False for "standalone=false", None if not provided
        if self._c_doc.standalone == -1:
            return None
        else:
            return <bint>(self._c_doc.standalone == 1)

    @cython.final
    cdef bytes buildNewPrefix(self):
        # get a new unique prefix ("nsX") for this document
        cdef bytes ns
        if self._ns_counter < len(_PREFIX_CACHE):
            ns = _PREFIX_CACHE[self._ns_counter]
        else:
            ns = python.PyBytes_FromFormat("ns%d", self._ns_counter)
        if self._prefix_tail is not None:
            ns += self._prefix_tail
        self._ns_counter += 1
        if self._ns_counter < 0:
            # overflow!
            self._ns_counter = 0
            if self._prefix_tail is None:
                self._prefix_tail = b"A"
            else:
                self._prefix_tail += b"A"
        return ns

    @cython.final
    cdef xmlNs* _findOrBuildNodeNs(self, xmlNode* c_node,
                                   const_xmlChar* c_href, const_xmlChar* c_prefix,
                                   bint is_attribute) except NULL:
        u"""Get or create namespace structure for a node.  Reuses the prefix if
        possible.
        """
        cdef xmlNs* c_ns
        cdef xmlNs* c_doc_ns
        cdef python.PyObject* dict_result
        if c_node.type != tree.XML_ELEMENT_NODE:
            assert c_node.type == tree.XML_ELEMENT_NODE, \
                u"invalid node type %d, expected %d" % (
                c_node.type, tree.XML_ELEMENT_NODE)
        # look for existing ns declaration
        c_ns = _searchNsByHref(c_node, c_href, is_attribute)
        if c_ns is not NULL:
            if is_attribute and c_ns.prefix is NULL:
                # do not put namespaced attributes into the default
                # namespace as this would break serialisation
                pass
            else:
                return c_ns

        # none found => determine a suitable new prefix
        if c_prefix is NULL:
            dict_result = python.PyDict_GetItem(
                _DEFAULT_NAMESPACE_PREFIXES, <unsigned char*>c_href)
            if dict_result is not NULL:
                prefix = <object>dict_result
            else:
                prefix = self.buildNewPrefix()
            c_prefix = _xcstr(prefix)

        # make sure the prefix is not in use already
        while tree.xmlSearchNs(self._c_doc, c_node, c_prefix) is not NULL:
            prefix = self.buildNewPrefix()
            c_prefix = _xcstr(prefix)

        # declare the namespace and return it
        c_ns = tree.xmlNewNs(c_node, c_href, c_prefix)
        if c_ns is NULL:
            raise MemoryError()
        return c_ns

    @cython.final
    cdef int _setNodeNs(self, xmlNode* c_node, const_xmlChar* c_href) except -1:
        u"Lookup namespace structure and set it for the node."
        c_ns = self._findOrBuildNodeNs(c_node, c_href, NULL, 0)
        tree.xmlSetNs(c_node, c_ns)

cdef tuple __initPrefixCache():
    cdef int i
    return tuple([ python.PyBytes_FromFormat("ns%d", i)
                   for i in range(30) ])

cdef tuple _PREFIX_CACHE = __initPrefixCache()

cdef _Document _documentFactory(xmlDoc* c_doc, _BaseParser parser):
    cdef _Document result
    result = _Document.__new__(_Document)
    result._c_doc = c_doc
    result._ns_counter = 0
    result._prefix_tail = None
    if parser is None:
        parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
    result._parser = parser
    return result


cdef object _find_invalid_public_id_characters = re.compile(
    ur"[^\x20\x0D\x0Aa-zA-Z0-9'()+,./:=?;!*#@$_%-]+").search


cdef class DocInfo:
    u"Document information provided by parser and DTD."
    cdef _Document _doc
    def __cinit__(self, tree):
        u"Create a DocInfo object for an ElementTree object or root Element."
        self._doc = _documentOrRaise(tree)
        root_name, public_id, system_url = self._doc.getdoctype()
        if not root_name and (public_id or system_url):
            raise ValueError, u"Could not find root node"

    property root_name:
        u"Returns the name of the root node as defined by the DOCTYPE."
        def __get__(self):
            root_name, public_id, system_url = self._doc.getdoctype()
            return root_name

    @cython.final
    cdef tree.xmlDtd* _get_c_dtd(self):
        u"""Return the DTD. Create it if it does not yet exist."""
        cdef xmlDoc* c_doc = self._doc._c_doc
        cdef xmlNode* c_root_node
        cdef const_xmlChar* c_name

        if c_doc.intSubset:
            return c_doc.intSubset

        c_root_node = tree.xmlDocGetRootElement(c_doc)
        c_name = c_root_node.name if c_root_node else NULL
        return  tree.xmlCreateIntSubset(c_doc, c_name, NULL, NULL)

    def clear(self):
        u"""Removes DOCTYPE and internal subset from the document."""
        cdef xmlDoc* c_doc = self._doc._c_doc
        cdef tree.xmlNode* c_dtd = <xmlNode*>c_doc.intSubset
        if c_dtd is NULL:
            return
        tree.xmlUnlinkNode(c_dtd)
        tree.xmlFreeNode(c_dtd)

    property public_id:
        u"""Public ID of the DOCTYPE.

        Mutable.  May be set to a valid string or None.  If a DTD does not
        exist, setting this variable (even to None) will create one.
        """
        def __get__(self):
            root_name, public_id, system_url = self._doc.getdoctype()
            return public_id

        def __set__(self, value):
            cdef xmlChar* c_value = NULL
            if value is not None:
                match = _find_invalid_public_id_characters(value)
                if match:
                    raise ValueError('Invalid character(s) %r in public_id.' % match.group(0))
                value = _utf8(value)
                c_value = tree.xmlStrdup(_xcstr(value))
                if not c_value:
                    raise MemoryError()

            c_dtd = self._get_c_dtd()
            if not c_dtd:
                tree.xmlFree(c_value)
                raise MemoryError()
            if c_dtd.ExternalID:
                tree.xmlFree(<void*>c_dtd.ExternalID)
            c_dtd.ExternalID = c_value

    property system_url:
        u"""System ID of the DOCTYPE.

        Mutable.  May be set to a valid string or None.  If a DTD does not
        exist, setting this variable (even to None) will create one.
        """
        def __get__(self):
            root_name, public_id, system_url = self._doc.getdoctype()
            return system_url

        def __set__(self, value):
            cdef xmlChar* c_value = NULL
            if value is not None:
                bvalue = _utf8(value)
                # sys_url may be any valid unicode string that can be
                # enclosed in single quotes or quotes.
                if b"'" in bvalue and b'"' in bvalue:
                    raise ValueError(
                        'System URL may not contain both single (\') and double quotes (").')
                c_value = tree.xmlStrdup(_xcstr(bvalue))
                if not c_value:
                    raise MemoryError()

            c_dtd = self._get_c_dtd()
            if not c_dtd:
                tree.xmlFree(c_value)
                raise MemoryError()
            if c_dtd.SystemID:
                tree.xmlFree(<void*>c_dtd.SystemID)
            c_dtd.SystemID = c_value

    property xml_version:
        u"Returns the XML version as declared by the document."
        def __get__(self):
            xml_version, encoding = self._doc.getxmlinfo()
            return xml_version

    property encoding:
        u"Returns the encoding name as declared by the document."
        def __get__(self):
            xml_version, encoding = self._doc.getxmlinfo()
            return encoding

    property standalone:
        u"""Returns the standalone flag as declared by the document.  The possible
        values are True (``standalone='yes'``), False
        (``standalone='no'`` or flag not provided in the declaration),
        and None (unknown or no declaration found).  Note that a
        normal truth test on this value will always tell if the
        ``standalone`` flag was set to ``'yes'`` or not.
        """
        def __get__(self):
            return self._doc.isstandalone()

    property URL:
        u"The source URL of the document (or None if unknown)."
        def __get__(self):
            if self._doc._c_doc.URL is NULL:
                return None
            return _decodeFilename(self._doc._c_doc.URL)
        def __set__(self, url):
            url = _encodeFilename(url)
            c_oldurl = self._doc._c_doc.URL
            if url is None:
                self._doc._c_doc.URL = NULL
            else:
                self._doc._c_doc.URL = tree.xmlStrdup(_xcstr(url))
            if c_oldurl is not NULL:
                tree.xmlFree(<void*>c_oldurl)

    property doctype:
        u"Returns a DOCTYPE declaration string for the document."
        def __get__(self):
            root_name, public_id, system_url = self._doc.getdoctype()
            if system_url:
                # If '"' in system_url, we must escape it with single
                # quotes, otherwise escape with double quotes. If url
                # contains both a single quote and a double quote, XML
                # standard is being violated.
                if '"' in system_url:
                    quoted_system_url = u"'%s'" % system_url
                else:
                    quoted_system_url = u'"%s"' % system_url
            if public_id:
                if system_url:
                    return u'<!DOCTYPE %s PUBLIC "%s" %s>' % (
                        root_name, public_id, quoted_system_url)
                else:
                    return u'<!DOCTYPE %s PUBLIC "%s">' % (
                        root_name, public_id)
            elif system_url:
                return u'<!DOCTYPE %s SYSTEM %s>' % (
                    root_name, quoted_system_url)
            elif self._doc.hasdoctype():
                return u'<!DOCTYPE %s>' % root_name
            else:
                return u""

    property internalDTD:
        u"Returns a DTD validator based on the internal subset of the document."
        def __get__(self):
            return _dtdFactory(self._doc._c_doc.intSubset)

    property externalDTD:
        u"Returns a DTD validator based on the external subset of the document."
        def __get__(self):
            return _dtdFactory(self._doc._c_doc.extSubset)


@cython.no_gc_clear
cdef public class _Element [ type LxmlElementType, object LxmlElement ]:
    u"""Element class.

    References a document object and a libxml node.

    By pointing to a Document instance, a reference is kept to
    _Document as long as there is some pointer to a node in it.
    """
    cdef _Document _doc
    cdef xmlNode* _c_node
    cdef object _tag

    def _init(self):
        u"""_init(self)

        Called after object initialisation.  Custom subclasses may override
        this if they recursively call _init() in the superclasses.
        """

    def __dealloc__(self):
        #print "trying to free node:", <int>self._c_node
        #displayNode(self._c_node, 0)
        if self._c_node is not NULL:
            _unregisterProxy(self)
            attemptDeallocation(self._c_node)

    # MANIPULATORS

    def __setitem__(self, x, value):
        u"""__setitem__(self, x, value)

        Replaces the given subelement index or slice.
        """
        cdef xmlNode* c_node = NULL
        cdef xmlNode* c_next
        cdef xmlDoc* c_source_doc
        cdef _Element element
        cdef bint left_to_right
        cdef Py_ssize_t slicelength = 0, step = 0
        _assertValidNode(self)
        if value is None:
            raise ValueError, u"cannot assign None"
        if isinstance(x, slice):
            # slice assignment
            _findChildSlice(<slice>x, self._c_node, &c_node, &step, &slicelength)
            if step > 0:
                left_to_right = 1
            else:
                left_to_right = 0
                step = -step
            _replaceSlice(self, c_node, slicelength, step, left_to_right, value)
            return
        else:
            # otherwise: normal item assignment
            element = value
            _assertValidNode(element)
            c_node = _findChild(self._c_node, x)
            if c_node is NULL:
                raise IndexError, u"list index out of range"
            c_source_doc = element._c_node.doc
            c_next = element._c_node.next
            _removeText(c_node.next)
            tree.xmlReplaceNode(c_node, element._c_node)
            _moveTail(c_next, element._c_node)
            moveNodeToDocument(self._doc, c_source_doc, element._c_node)
            if not attemptDeallocation(c_node):
                moveNodeToDocument(self._doc, c_node.doc, c_node)

    def __delitem__(self, x):
        u"""__delitem__(self, x)

        Deletes the given subelement or a slice.
        """
        cdef xmlNode* c_node = NULL
        cdef xmlNode* c_next
        cdef Py_ssize_t step = 0, slicelength = 0
        _assertValidNode(self)
        if isinstance(x, slice):
            # slice deletion
            if _isFullSlice(<slice>x):
                c_node = self._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:
                        c_next = _nextElement(c_node)
                        _removeNode(self._doc, c_node)
                        c_node = c_next
            else:
                _findChildSlice(<slice>x, self._c_node, &c_node, &step, &slicelength)
                _deleteSlice(self._doc, c_node, slicelength, step)
        else:
            # item deletion
            c_node = _findChild(self._c_node, x)
            if c_node is NULL:
                raise IndexError, u"index out of range: %d" % x
            _removeText(c_node.next)
            _removeNode(self._doc, c_node)

    def __deepcopy__(self, memo):
        u"__deepcopy__(self, memo)"
        return self.__copy__()

    def __copy__(self):
        u"__copy__(self)"
        cdef xmlDoc* c_doc
        cdef xmlNode* c_node
        cdef _Document new_doc
        _assertValidNode(self)
        c_doc = _copyDocRoot(self._doc._c_doc, self._c_node) # recursive
        new_doc = _documentFactory(c_doc, self._doc._parser)
        root = new_doc.getroot()
        if root is not None:
            return root
        # Comment/PI
        c_node = c_doc.children
        while c_node is not NULL and c_node.type != self._c_node.type:
            c_node = c_node.next
        if c_node is NULL:
            return None
        return _elementFactory(new_doc, c_node)

    def set(self, key, value):
        u"""set(self, key, value)

        Sets an element attribute.
        """
        _assertValidNode(self)
        _setAttributeValue(self, key, value)

    def append(self, _Element element not None):
        u"""append(self, element)

        Adds a subelement to the end of this element.
        """
        _assertValidNode(self)
        _assertValidNode(element)
        _appendChild(self, element)

    def addnext(self, _Element element not None):
        u"""addnext(self, element)

        Adds the element as a following sibling directly after this
        element.

        This is normally used to set a processing instruction or comment after
        the root node of a document.  Note that tail text is automatically
        discarded when adding at the root level.
        """
        _assertValidNode(self)
        _assertValidNode(element)
        if self._c_node.parent != NULL and not _isElement(self._c_node.parent):
            if element._c_node.type != tree.XML_PI_NODE:
                if element._c_node.type != tree.XML_COMMENT_NODE:
                    raise TypeError, u"Only processing instructions and comments can be siblings of the root element"
            element.tail = None
        _appendSibling(self, element)

    def addprevious(self, _Element element not None):
        u"""addprevious(self, element)

        Adds the element as a preceding sibling directly before this
        element.

        This is normally used to set a processing instruction or comment
        before the root node of a document.  Note that tail text is
        automatically discarded when adding at the root level.
        """
        _assertValidNode(self)
        _assertValidNode(element)
        if self._c_node.parent != NULL and not _isElement(self._c_node.parent):
            if element._c_node.type != tree.XML_PI_NODE:
                if element._c_node.type != tree.XML_COMMENT_NODE:
                    raise TypeError, u"Only processing instructions and comments can be siblings of the root element"
            element.tail = None
        _prependSibling(self, element)

    def extend(self, elements):
        u"""extend(self, elements)

        Extends the current children by the elements in the iterable.
        """
        cdef _Element element
        _assertValidNode(self)
        for element in elements:
            if element is None:
                raise TypeError, u"Node must not be None"
            _assertValidNode(element)
            _appendChild(self, element)

    def clear(self):
        u"""clear(self)

        Resets an element.  This function removes all subelements, clears
        all attributes and sets the text and tail properties to None.
        """
        cdef xmlAttr* c_attr
        cdef xmlAttr* c_attr_next
        cdef xmlNode* c_node
        cdef xmlNode* c_node_next
        _assertValidNode(self)
        c_node = self._c_node
        # remove self.text and self.tail
        _removeText(c_node.children)
        _removeText(c_node.next)
        # remove all attributes
        c_attr = c_node.properties
        while c_attr is not NULL:
            c_attr_next = c_attr.next
            tree.xmlRemoveProp(c_attr)
            c_attr = c_attr_next
        # remove all subelements
        c_node = 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:
                c_node_next = _nextElement(c_node)
                _removeNode(self._doc, c_node)
                c_node = c_node_next

    def insert(self, index, _Element element not None):
        u"""insert(self, index, element)

        Inserts a subelement at the given position in this element
        """
        cdef xmlNode* c_node
        cdef xmlNode* c_next
        cdef xmlDoc* c_source_doc
        _assertValidNode(self)
        _assertValidNode(element)
        c_node = _findChild(self._c_node, index)
        if c_node is NULL:
            _appendChild(self, element)
            return
        c_source_doc = c_node.doc
        c_next = element._c_node.next
        tree.xmlAddPrevSibling(c_node, element._c_node)
        _moveTail(c_next, element._c_node)
        moveNodeToDocument(self._doc, c_source_doc, element._c_node)

    def remove(self, _Element element not None):
        u"""remove(self, element)

        Removes a matching subelement. Unlike the find methods, this
        method compares elements based on identity, not on tag value
        or contents.
        """
        cdef xmlNode* c_node
        cdef xmlNode* c_next
        _assertValidNode(self)
        _assertValidNode(element)
        c_node = element._c_node
        if c_node.parent is not self._c_node:
            raise ValueError, u"Element is not a child of this node."
        c_next = element._c_node.next
        tree.xmlUnlinkNode(c_node)
        _moveTail(c_next, c_node)
        # fix namespace declarations
        moveNodeToDocument(self._doc, c_node.doc, c_node)

    def replace(self, _Element old_element not None,
                _Element new_element not None):
        u"""replace(self, old_element, new_element)

        Replaces a subelement with the element passed as second argument.
        """
        cdef xmlNode* c_old_node
        cdef xmlNode* c_old_next
        cdef xmlNode* c_new_node
        cdef xmlNode* c_new_next
        cdef xmlDoc* c_source_doc
        _assertValidNode(self)
        _assertValidNode(old_element)
        _assertValidNode(new_element)
        c_old_node = old_element._c_node
        if c_old_node.parent is not self._c_node:
            raise ValueError, u"Element is not a child of this node."
        c_old_next = c_old_node.next
        c_new_node = new_element._c_node
        c_new_next = c_new_node.next
        c_source_doc = c_new_node.doc
        tree.xmlReplaceNode(c_old_node, c_new_node)
        _moveTail(c_new_next, c_new_node)
        _moveTail(c_old_next, c_old_node)
        moveNodeToDocument(self._doc, c_source_doc, c_new_node)
        # fix namespace declarations
        moveNodeToDocument(self._doc, c_old_node.doc, c_old_node)

    # PROPERTIES
    property tag:
        u"""Element tag
        """
        def __get__(self):
            if self._tag is not None:
                return self._tag
            _assertValidNode(self)
            self._tag = _namespacedName(self._c_node)
            return self._tag

        def __set__(self, value):
            cdef _BaseParser parser
            _assertValidNode(self)
            ns, name = _getNsTag(value)
            parser = self._doc._parser
            if parser is not None and parser._for_html:
                _htmlTagValidOrRaise(name)
            else:
                _tagValidOrRaise(name)
            self._tag = value
            tree.xmlNodeSetName(self._c_node, _xcstr(name))
            if ns is None:
                self._c_node.ns = NULL
            else:
                self._doc._setNodeNs(self._c_node, _xcstr(ns))

    property attrib:
        u"""Element attribute dictionary. Where possible, use get(), set(),
        keys(), values() and items() to access element attributes.
        """
        def __get__(self):
            return _Attrib.__new__(_Attrib, self)

    property text:
        u"""Text before the first subelement. This is either a string or
        the value None, if there was no text.
        """
        def __get__(self):
            _assertValidNode(self)
            return _collectText(self._c_node.children)

        def __set__(self, value):
            _assertValidNode(self)
            if isinstance(value, QName):
                value = _resolveQNameText(self, value).decode('utf8')
            _setNodeText(self._c_node, value)

        # using 'del el.text' is the wrong thing to do
        #def __del__(self):
        #    _setNodeText(self._c_node, None)

    property tail:
        u"""Text after this element's end tag, but before the next sibling
        element's start tag. This is either a string or the value None, if
        there was no text.
        """
        def __get__(self):
            _assertValidNode(self)
            return _collectText(self._c_node.next)

        def __set__(self, value):
            _assertValidNode(self)
            _setTailText(self._c_node, value)

        # using 'del el.tail' is the wrong thing to do
        #def __del__(self):
        #    _setTailText(self._c_node, None)

    # not in ElementTree, read-only
    property prefix:
        u"""Namespace prefix or None.
        """
        def __get__(self):
            if self._c_node.ns is not NULL:
                if self._c_node.ns.prefix is not NULL:
                    return funicode(self._c_node.ns.prefix)
            return None

    # not in ElementTree, read-only
    property sourceline:
        u"""Original line number as found by the parser or None if unknown.
        """
        def __get__(self):
            cdef long line
            _assertValidNode(self)
            line = tree.xmlGetLineNo(self._c_node)
            return line if line > 0 else None

        def __set__(self, line):
            _assertValidNode(self)
            if line <= 0:
                self._c_node.line = 0
            else:
                self._c_node.line = line

    # not in ElementTree, read-only
    property nsmap:
        u"""Namespace prefix->URI mapping known in the context of this
        Element.  This includes all namespace declarations of the
        parents.

        Note that changing the returned dict has no effect on the Element.
        """
        def __get__(self):
            cdef xmlNode* c_node
            cdef xmlNs* c_ns
            _assertValidNode(self)
            nsmap = {}
            c_node = self._c_node
            while c_node is not NULL and c_node.type == tree.XML_ELEMENT_NODE:
                c_ns = c_node.nsDef
                while c_ns is not NULL:
                    prefix = funicodeOrNone(c_ns.prefix)
                    if prefix not in nsmap:
                        nsmap[prefix] = funicodeOrNone(c_ns.href)
                    c_ns = c_ns.next
                c_node = c_node.parent
            return nsmap

    # not in ElementTree, read-only
    property base:
        u"""The base URI of the Element (xml:base or HTML base URL).
        None if the base URI is unknown.

        Note that the value depends on the URL of the document that
        holds the Element if there is no xml:base attribute on the
        Element or its ancestors.

        Setting this property will set an xml:base attribute on the
        Element, regardless of the document type (XML or HTML).
        """
        def __get__(self):
            _assertValidNode(self)
            c_base = tree.xmlNodeGetBase(self._doc._c_doc, self._c_node)
            if c_base is NULL:
                if self._doc._c_doc.URL is NULL:
                    return None
                return _decodeFilename(self._doc._c_doc.URL)
            try:
                base = _decodeFilename(c_base)
            finally:
                tree.xmlFree(c_base)
            return base

        def __set__(self, url):
            _assertValidNode(self)
            if url is None:
                c_base = <const_xmlChar*>NULL
            else:
                url = _encodeFilename(url)
                c_base = _xcstr(url)
            tree.xmlNodeSetBase(self._c_node, c_base)

    # ACCESSORS
    def __repr__(self):
        u"__repr__(self)"
        return "<Element %s at 0x%x>" % (strrepr(self.tag), id(self))

    def __getitem__(self, x):
        u"""Returns the subelement at the given position or the requested
        slice.
        """
        cdef xmlNode* c_node = NULL
        cdef Py_ssize_t step = 0, slicelength = 0
        cdef Py_ssize_t c, i
        cdef _node_to_node_function next_element
        cdef list result
        _assertValidNode(self)
        if isinstance(x, slice):
            # slicing
            if _isFullSlice(<slice>x):
                return _collectChildren(self)
            _findChildSlice(<slice>x, self._c_node, &c_node, &step, &slicelength)
            if c_node is NULL:
                return []
            if step > 0:
                next_element = _nextElement
            else:
                step = -step
                next_element = _previousElement
            result = []
            c = 0
            while c_node is not NULL and c < slicelength:
                result.append(_elementFactory(self._doc, c_node))
                c += 1
                for i in range(step):
                    c_node = next_element(c_node)
            return result
        else:
            # indexing
            c_node = _findChild(self._c_node, x)
            if c_node is NULL:
                raise IndexError, u"list index out of range"
            return _elementFactory(self._doc, c_node)

    def __len__(self):
        u"""__len__(self)

        Returns the number of subelements.
        """
        _assertValidNode(self)
        return _countElements(self._c_node.children)

    def __nonzero__(self):
        #u"__nonzero__(self)" # currently fails in Py3.1
        import warnings
        warnings.warn(
            u"The behavior of this method will change in future versions. "
            u"Use specific 'len(elem)' or 'elem is not None' test instead.",
            FutureWarning
            )
        # emulate old behaviour
        _assertValidNode(self)
        return _hasChild(self._c_node)

    def __contains__(self, element):
        u"__contains__(self, element)"
        cdef xmlNode* c_node
        _assertValidNode(self)
        if not isinstance(element, _Element):
            return 0
        c_node = (<_Element>element)._c_node
        return c_node is not NULL and c_node.parent is self._c_node

    def __iter__(self):
        u"__iter__(self)"
        return ElementChildIterator(self)

    def __reversed__(self):
        u"__reversed__(self)"
        return ElementChildIterator(self, reversed=True)

    def index(self, _Element child not None, start=None, stop=None):
        u"""index(self, child, start=None, stop=None)

        Find the position of the child within the parent.

        This method is not part of the original ElementTree API.
        """
        cdef Py_ssize_t k, l
        cdef Py_ssize_t c_start, c_stop
        cdef xmlNode* c_child
        cdef xmlNode* c_start_node
        _assertValidNode(self)
        _assertValidNode(child)
        c_child = child._c_node
        if c_child.parent is not self._c_node:
            raise ValueError, u"Element is not a child of this node."

        # handle the unbounded search straight away (normal case)
        if stop is None and (start is None or start == 0):
            k = 0
            c_child = c_child.prev
            while c_child is not NULL:
                if _isElement(c_child):
                    k += 1
                c_child = c_child.prev
            return k

        # check indices
        if start is None:
            c_start = 0
        else:
            c_start = start
        if stop is None:
            c_stop = 0
        else:
            c_stop = stop
            if c_stop == 0 or \
                   c_start >= c_stop and (c_stop > 0 or c_start < 0):
                raise ValueError, u"list.index(x): x not in slice"

        # for negative slice indices, check slice before searching index
        if c_start < 0 or c_stop < 0:
            # start from right, at most up to leftmost(c_start, c_stop)
            if c_start < c_stop:
                k = -c_start
            else:
                k = -c_stop
            c_start_node = self._c_node.last
            l = 1
            while c_start_node != c_child and l < k:
                if _isElement(c_start_node):
                    l += 1
                c_start_node = c_start_node.prev
            if c_start_node == c_child:
                # found! before slice end?
                if c_stop < 0 and l <= -c_stop:
                    raise ValueError, u"list.index(x): x not in slice"
            elif c_start < 0:
                raise ValueError, u"list.index(x): x not in slice"

        # now determine the index backwards from child
        c_child = c_child.prev
        k = 0
        if c_stop > 0:
            # we can optimize: stop after c_stop elements if not found
            while c_child != NULL and k < c_stop:
                if _isElement(c_child):
                    k += 1
                c_child = c_child.prev
            if k < c_stop:
                return k
        else:
            # traverse all
            while c_child != NULL:
                if _isElement(c_child):
                    k = k + 1
                c_child = c_child.prev
            if c_start > 0:
                if k >= c_start:
                    return k
            else:
                return k
        if c_start != 0 or c_stop != 0:
            raise ValueError, u"list.index(x): x not in slice"
        else:
            raise ValueError, u"list.index(x): x not in list"

    def get(self, key, default=None):
        u"""get(self, key, default=None)

        Gets an element attribute.
        """
        _assertValidNode(self)
        return _getAttributeValue(self, key, default)

    def keys(self):
        u"""keys(self)

        Gets a list of attribute names.  The names are returned in an
        arbitrary order (just like for an ordinary Python dictionary).
        """
        _assertValidNode(self)
        return _collectAttributes(self._c_node, 1)

    def values(self):
        u"""values(self)

        Gets element attribute values as a sequence of strings.  The
        attributes are returned in an arbitrary order.
        """
        _assertValidNode(self)
        return _collectAttributes(self._c_node, 2)

    def items(self):
        u"""items(self)

        Gets element attributes, as a sequence. The attributes are returned in
        an arbitrary order.
        """
        _assertValidNode(self)
        return _collectAttributes(self._c_node, 3)

    def getchildren(self):
        u"""getchildren(self)

        Returns all direct children.  The elements are returned in document
        order.

        :deprecated: Note that this method has been deprecated as of
          ElementTree 1.3 and lxml 2.0.  New code should use
          ``list(element)`` or simply iterate over elements.
        """
        _assertValidNode(self)
        return _collectChildren(self)

    def getparent(self):
        u"""getparent(self)

        Returns the parent of this element or None for the root element.
        """
        cdef xmlNode* c_node
        #_assertValidNode(self) # not needed
        c_node = _parentElement(self._c_node)
        if c_node is NULL:
            return None
        return _elementFactory(self._doc, c_node)

    def getnext(self):
        u"""getnext(self)

        Returns the following sibling of this element or None.
        """
        cdef xmlNode* c_node
        #_assertValidNode(self) # not needed
        c_node = _nextElement(self._c_node)
        if c_node is NULL:
            return None
        return _elementFactory(self._doc, c_node)

    def getprevious(self):
        u"""getprevious(self)

        Returns the preceding sibling of this element or None.
        """
        cdef xmlNode* c_node
        #_assertValidNode(self) # not needed
        c_node = _previousElement(self._c_node)
        if c_node is NULL:
            return None
        return _elementFactory(self._doc, c_node)

    def itersiblings(self, tag=None, *tags, preceding=False):
        u"""itersiblings(self, tag=None, *tags, preceding=False)

        Iterate over the following or preceding siblings of this element.

        The direction is determined by the 'preceding' keyword which
        defaults to False, i.e. forward iteration over the following
        siblings.  When True, the iterator yields the preceding
        siblings in reverse document order, i.e. starting right before
        the current element and going backwards.

        Can be restricted to find only elements with a specific tag,
        see `iter`.
        """
        if tag is not None:
            tags += (tag,)
        return SiblingsIterator(self, tags, preceding=preceding)

    def iterancestors(self, tag=None, *tags):
        u"""iterancestors(self, tag=None, *tags)

        Iterate over the ancestors of this element (from parent to parent).

        Can be restricted to find only elements with a specific tag,
        see `iter`.
        """
        if tag is not None:
            tags += (tag,)
        return AncestorsIterator(self, tags)

    def iterdescendants(self, tag=None, *tags):
        u"""iterdescendants(self, tag=None, *tags)

        Iterate over the descendants of this element in document order.

        As opposed to ``el.iter()``, this iterator does not yield the element
        itself.  The returned elements can be restricted to find only elements
        with a specific tag, see `iter`.
        """
        if tag is not None:
            tags += (tag,)
        return ElementDepthFirstIterator(self, tags, inclusive=False)

    def iterchildren(self, tag=None, *tags, reversed=False):
        u"""iterchildren(self, tag=None, *tags, reversed=False)

        Iterate over the children of this element.

        As opposed to using normal iteration on this element, the returned
        elements can be reversed with the 'reversed' keyword and restricted
        to find only elements with a specific tag, see `iter`.
        """
        if tag is not None:
            tags += (tag,)
        return ElementChildIterator(self, tags, reversed=reversed)

    def getroottree(self):
        u"""getroottree(self)

        Return an ElementTree for the root node of the document that
        contains this element.

        This is the same as following element.getparent() up the tree until it
        returns None (for the root element) and then build an ElementTree for
        the last parent that was returned."""
        _assertValidDoc(self._doc)
        return _elementTreeFactory(self._doc, None)

    def getiterator(self, tag=None, *tags):
        u"""getiterator(self, tag=None, *tags)

        Returns a sequence or iterator of all elements in the subtree in
        document order (depth first pre-order), starting with this
        element.

        Can be restricted to find only elements with a specific tag,
        see `iter`.

        :deprecated: Note that this method is deprecated as of
          ElementTree 1.3 and lxml 2.0.  It returns an iterator in
          lxml, which diverges from the original ElementTree
          behaviour.  If you want an efficient iterator, use the
          ``element.iter()`` method instead.  You should only use this
          method in new code if you require backwards compatibility
          with older versions of lxml or ElementTree.
        """
        if tag is not None:
            tags += (tag,)
        return ElementDepthFirstIterator(self, tags)

    def iter(self, tag=None, *tags):
        u"""iter(self, tag=None, *tags)

        Iterate over all elements in the subtree in document order (depth
        first pre-order), starting with this element.

        Can be restricted to find only elements with a specific tag:
        pass ``"{ns}localname"`` as tag. Either or both of ``ns`` and
        ``localname`` can be ``*`` for a wildcard; ``ns`` can be empty
        for no namespace. ``"localname"`` is equivalent to ``"{}localname"``
        (i.e. no namespace) but ``"*"`` is ``"{*}*"`` (any or no namespace),
        not ``"{}*"``.

        You can also pass the Element, Comment, ProcessingInstruction and
        Entity factory functions to look only for the specific element type.

        Passing more than one tag will let the iterator return all elements
        matching any of these tags, in document order.
        """
        if tag is not None:
            tags += (tag,)
        return ElementDepthFirstIterator(self, tags)

    def itertext(self, tag=None, *tags, with_tail=True):
        u"""itertext(self, tag=None, *tags, with_tail=True)

        Iterates over the text content of a subtree.

        You can pass a tag name to restrict text content to specific elements,
        see `iter`.

        You can set the ``with_tail`` keyword argument to ``False`` to skip
        over tail text.
        """
        if tag is not None:
            tags += (tag,)
        return ElementTextIterator(self, tags, with_tail=with_tail)

    def makeelement(self, _tag, attrib=None, nsmap=None, **_extra):
        u"""makeelement(self, _tag, attrib=None, nsmap=None, **_extra)

        Creates a new element associated with the same document.
        """
        _assertValidDoc(self._doc)
        return _makeElement(_tag, NULL, self._doc, None, None, None,
                            attrib, nsmap, _extra)

    def find(self, path, namespaces=None):
        u"""find(self, path, namespaces=None)

        Finds the first matching subelement, by tag name or path.

        The optional ``namespaces`` argument accepts a
        prefix-to-namespace mapping that allows the usage of XPath
        prefixes in the path expression.
        """
        if isinstance(path, QName):
            path = (<QName>path).text
        return _elementpath.find(self, path, namespaces)

    def findtext(self, path, default=None, namespaces=None):
        u"""findtext(self, path, default=None, namespaces=None)

        Finds text for the first matching subelement, by tag name or path.

        The optional ``namespaces`` argument accepts a
        prefix-to-namespace mapping that allows the usage of XPath
        prefixes in the path expression.
        """
        if isinstance(path, QName):
            path = (<QName>path).text
        return _elementpath.findtext(self, path, default, namespaces)

    def findall(self, path, namespaces=None):
        u"""findall(self, path, namespaces=None)

        Finds all matching subelements, by tag name or path.

        The optional ``namespaces`` argument accepts a
        prefix-to-namespace mapping that allows the usage of XPath
        prefixes in the path expression.
        """
        if isinstance(path, QName):
            path = (<QName>path).text
        return _elementpath.findall(self, path, namespaces)

    def iterfind(self, path, namespaces=None):
        u"""iterfind(self, path, namespaces=None)

        Iterates over all matching subelements, by tag name or path.

        The optional ``namespaces`` argument accepts a
        prefix-to-namespace mapping that allows the usage of XPath
        prefixes in the path expression.
        """
        if isinstance(path, QName):
            path = (<QName>path).text
        return _elementpath.iterfind(self, path, namespaces)

    def xpath(self, _path, *, namespaces=None, extensions=None,
              smart_strings=True, **_variables):
        u"""xpath(self, _path, namespaces=None, extensions=None, smart_strings=True, **_variables)

        Evaluate an xpath expression using the element as context node.
        """
        evaluator = XPathElementEvaluator(self, namespaces=namespaces,
                                          extensions=extensions,
                                          smart_strings=smart_strings)
        return evaluator(_path, **_variables)

    def cssselect(self, expr, *, translator='xml'):
        """
        Run the CSS expression on this element and its children,
        returning a list of the results.

        Equivalent to lxml.cssselect.CSSSelect(expr)(self) -- note
        that pre-compiling the expression can provide a substantial
        speedup.
        """
        # Do the import here to make the dependency optional.
        from lxml.cssselect import CSSSelector
        return CSSSelector(expr, translator=translator)(self)


cdef extern from "etree_defs.h":
    # macro call to 't->tp_new()' for fast instantiation
    cdef object NEW_ELEMENT "PY_NEW" (object t)


@cython.linetrace(False)
cdef _Element _elementFactory(_Document doc, xmlNode* c_node):
    cdef _Element result
    result = getProxy(c_node)
    if result is not None:
        return result
    if c_node is NULL:
        return None

    element_class = LOOKUP_ELEMENT_CLASS(
        ELEMENT_CLASS_LOOKUP_STATE, doc, c_node)
    if hasProxy(c_node):
        # prevent re-entry race condition - we just called into Python
        return getProxy(c_node)
    result = NEW_ELEMENT(element_class)
    if hasProxy(c_node):
        # prevent re-entry race condition - we just called into Python
        result._c_node = NULL
        return getProxy(c_node)

    _registerProxy(result, doc, c_node)
    if element_class is not _Element:
        result._init()
    return result


@cython.internal
cdef class __ContentOnlyElement(_Element):
    cdef int _raiseImmutable(self) except -1:
        raise TypeError, u"this element does not have children or attributes"

    def set(self, key, value):
        u"set(self, key, value)"
        self._raiseImmutable()

    def append(self, value):
        u"append(self, value)"
        self._raiseImmutable()

    def insert(self, index, value):
        u"insert(self, index, value)"
        self._raiseImmutable()

    def __setitem__(self, index, value):
        u"__setitem__(self, index, value)"
        self._raiseImmutable()

    property attrib:
        def __get__(self):
            return IMMUTABLE_EMPTY_MAPPING

    property text:
        def __get__(self):
            _assertValidNode(self)
            return funicodeOrEmpty(self._c_node.content)

        def __set__(self, value):
            cdef tree.xmlDict* c_dict
            _assertValidNode(self)
            if value is None:
                c_text = <const_xmlChar*>NULL
            else:
                value = _utf8(value)
                c_text = _xcstr(value)
            tree.xmlNodeSetContent(self._c_node, c_text)

    # ACCESSORS
    def __getitem__(self, x):
        u"__getitem__(self, x)"
        if isinstance(x, slice):
            return []
        else:
            raise IndexError, u"list index out of range"

    def __len__(self):
        u"__len__(self)"
        return 0

    def get(self, key, default=None):
        u"get(self, key, default=None)"
        return None

    def keys(self):
        u"keys(self)"
        return []

    def items(self):
        u"items(self)"
        return []

    def values(self):
        u"values(self)"
        return []

cdef class _Comment(__ContentOnlyElement):
    property tag:
        def __get__(self):
            return Comment

    def __repr__(self):
        return "<!--%s-->" % strrepr(self.text)

cdef class _ProcessingInstruction(__ContentOnlyElement):
    property tag:
        def __get__(self):
            return ProcessingInstruction

    property target:
        # not in ElementTree
        def __get__(self):
            _assertValidNode(self)
            return funicode(self._c_node.name)

        def __set__(self, value):
            _assertValidNode(self)
            value = _utf8(value)
            c_text = _xcstr(value)
            tree.xmlNodeSetName(self._c_node, c_text)

    def __repr__(self):
        text = self.text
        if text:
            return "<?%s %s?>" % (strrepr(self.target),
                                  strrepr(text))
        else:
            return "<?%s?>" % strrepr(self.target)

    def get(self, key, default=None):
        u"""get(self, key, default=None)

        Try to parse pseudo-attributes from the text content of the
        processing instruction, search for one with the given key as
        name and return its associated value.

        Note that this is only a convenience method for the most
        common case that all text content is structured in
        attribute-like name-value pairs with properly quoted values.
        It is not guaranteed to work for all possible text content.
        """
        return self.attrib.get(key, default)

    property attrib:
        u"""Returns a dict containing all pseudo-attributes that can be
        parsed from the text content of this processing instruction.
        Note that modifying the dict currently has no effect on the
        XML node, although this is not guaranteed to stay this way.
        """
        def __get__(self):
            return { attr : (value1 or value2)
                     for attr, value1, value2 in _FIND_PI_ATTRIBUTES(u' ' + self.text) }

cdef object _FIND_PI_ATTRIBUTES = re.compile(ur'\s+(\w+)\s*=\s*(?:\'([^\']*)\'|"([^"]*)")', re.U).findall

cdef class _Entity(__ContentOnlyElement):
    property tag:
        def __get__(self):
            return Entity

    property name:
        # not in ElementTree
        def __get__(self):
            _assertValidNode(self)
            return funicode(self._c_node.name)

        def __set__(self, value):
            _assertValidNode(self)
            value_utf = _utf8(value)
            if b'&' in value_utf or b';' in value_utf:
                raise ValueError(u"Invalid entity name '%s'" % value)
            tree.xmlNodeSetName(self._c_node, _xcstr(value_utf))

    property text:
        # FIXME: should this be None or '&[VALUE];' or the resolved
        # entity value ?
        def __get__(self):
            _assertValidNode(self)
            return u'&%s;' % funicode(self._c_node.name)

    def __repr__(self):
        return "&%s;" % strrepr(self.name)


cdef class QName:
    u"""QName(text_or_uri_or_element, tag=None)

    QName wrapper for qualified XML names.

    Pass a tag name by itself or a namespace URI and a tag name to
    create a qualified name.  Alternatively, pass an Element to
    extract its tag name.

    The ``text`` property holds the qualified name in
    ``{namespace}tagname`` notation.  The ``namespace`` and
    ``localname`` properties hold the respective parts of the tag
    name.

    You can pass QName objects wherever a tag name is expected.  Also,
    setting Element text from a QName will resolve the namespace
    prefix and set a qualified text value.  This is helpful in XML
    languages like SOAP or XML-Schema that use prefixed tag names in
    their text content.
    """
    cdef readonly unicode text
    cdef readonly unicode localname
    cdef readonly unicode namespace
    def __init__(self, text_or_uri_or_element, tag=None):
        if not _isString(text_or_uri_or_element):
            if isinstance(text_or_uri_or_element, _Element):
                text_or_uri_or_element = (<_Element>text_or_uri_or_element).tag
                if not _isString(text_or_uri_or_element):
                    raise ValueError, (u"Invalid input tag of type %r" %
                                       type(text_or_uri_or_element))
            elif isinstance(text_or_uri_or_element, QName):
                text_or_uri_or_element = (<QName>text_or_uri_or_element).text
            else:
                text_or_uri_or_element = unicode(text_or_uri_or_element)

        ns_utf, tag_utf = _getNsTag(text_or_uri_or_element)
        if tag is not None:
            # either ('ns', 'tag') or ('{ns}oldtag', 'newtag')
            if ns_utf is None:
                ns_utf = tag_utf # case 1: namespace ended up as tag name
            tag_utf = _utf8(tag)
        _tagValidOrRaise(tag_utf)
        self.localname = (<bytes>tag_utf).decode('utf8')
        if ns_utf is None:
            self.namespace = None
            self.text = self.localname
        else:
            self.namespace = (<bytes>ns_utf).decode('utf8')
            self.text = u"{%s}%s" % (self.namespace, self.localname)
    def __str__(self):
        return self.text
    def __hash__(self):
        return hash(self.text)
    def __richcmp__(one, other, int op):
        try:
            if type(one) is QName:
                one = (<QName>one).text
            elif not isinstance(one, unicode):
                one = unicode(one)
            if type(other) is QName:
                other = (<QName>other).text
            elif not isinstance(other, unicode):
                other = unicode(other)
        except (ValueError, UnicodeDecodeError):
            return NotImplemented
        return python.PyObject_RichCompare(one, other, op)


cdef public class _ElementTree [ type LxmlElementTreeType,
                                 object LxmlElementTree ]:
    cdef _Document _doc
    cdef _Element _context_node

    # Note that _doc is only used to store the original document if we do not
    # have a _context_node.  All methods should prefer self._context_node._doc
    # to honour tree restructuring.  _doc can happily be None!

    @cython.final
    cdef int _assertHasRoot(self) except -1:
        u"""We have to take care here: the document may not have a root node!
        This can happen if ElementTree() is called without any argument and
        the caller 'forgets' to call parse() afterwards, so this is a bug in
        the caller program.
        """
        assert self._context_node is not None, \
               u"ElementTree not initialized, missing root"
        return 0

    def parse(self, source, _BaseParser parser=None, *, base_url=None):
        u"""parse(self, source, parser=None, base_url=None)

        Updates self with the content of source and returns its root
        """
        cdef _Document doc = None
        try:
            doc = _parseDocument(source, parser, base_url)
            self._context_node = doc.getroot()
            if self._context_node is None:
                self._doc = doc
        except _TargetParserResult as result_container:
            # raises a TypeError if we don't get an _Element
            self._context_node = result_container.result
        return self._context_node

    def _setroot(self, _Element root not None):
        u"""_setroot(self, root)

        Relocate the ElementTree to a new root node.
        """
        _assertValidNode(root)
        if root._c_node.type != tree.XML_ELEMENT_NODE:
            raise TypeError, u"Only elements can be the root of an ElementTree"
        self._context_node = root
        self._doc = None

    def getroot(self):
        u"""getroot(self)

        Gets the root element for this tree.
        """
        return self._context_node

    def __copy__(self):
        return _elementTreeFactory(self._doc, self._context_node)

    def __deepcopy__(self, memo):
        cdef _Element root
        cdef _Document doc
        cdef xmlDoc* c_doc
        if self._context_node is not None:
            root = self._context_node.__copy__()
            assert root is not None
            _assertValidNode(root)
            _copyNonElementSiblings(self._context_node._c_node, root._c_node)
            return _elementTreeFactory(None, root)
        elif self._doc is not None:
            _assertValidDoc(self._doc)
            c_doc = tree.xmlCopyDoc(self._doc._c_doc, 1)
            if c_doc is NULL:
                raise MemoryError()
            doc = _documentFactory(c_doc, self._doc._parser)
            return _elementTreeFactory(doc, None)
        else:
            # so what ...
            return self

    # not in ElementTree
    property docinfo:
        u"""Information about the document provided by parser and DTD."""
        def __get__(self):
            self._assertHasRoot()
            return DocInfo(self._context_node._doc)

    # not in ElementTree, read-only
    property parser:
        u"""The parser that was used to parse the document in this ElementTree.
        """
        def __get__(self):
            if self._context_node is not None and \
                   self._context_node._doc is not None:
                return self._context_node._doc._parser
            if self._doc is not None:
                return self._doc._parser
            return None

    def write(self, file, *, encoding=None, method=u"xml",
              pretty_print=False, xml_declaration=None, with_tail=True,
              standalone=None, doctype=None, compression=0,
              exclusive=False, with_comments=True, inclusive_ns_prefixes=None,
              docstring=None):
        u"""write(self, file, encoding=None, method="xml",
                  pretty_print=False, xml_declaration=None, with_tail=True,
                  standalone=None, doctype=None, compression=0,
                  exclusive=False, with_comments=True, inclusive_ns_prefixes=None)

        Write the tree to a filename, file or file-like object.

        Defaults to ASCII encoding and writing a declaration as needed.

        The keyword argument 'method' selects the output method:
        'xml', 'html', 'text' or 'c14n'.  Default is 'xml'.

        The ``exclusive`` and ``with_comments`` arguments are only
        used with C14N output, where they request exclusive and
        uncommented C14N serialisation respectively.

        Passing a boolean value to the ``standalone`` option will
        output an XML declaration with the corresponding
        ``standalone`` flag.

        The ``doctype`` option allows passing in a plain string that will
        be serialised before the XML tree.  Note that passing in non
        well-formed content here will make the XML output non well-formed.
        Also, an existing doctype in the document tree will not be removed
        when serialising an ElementTree instance.

        The ``compression`` option enables GZip compression level 1-9.

        The ``inclusive_ns_prefixes`` should be a list of namespace strings
        (i.e. ['xs', 'xsi']) that will be promoted to the top-level element
        during exclusive C14N serialisation.  This parameter is ignored if
        exclusive mode=False.

        If exclusive=True and no list is provided, a namespace will only be
        rendered if it is used by the immediate parent or one of its attributes
        and its prefix and values have not already been rendered by an ancestor
        of the namespace node's parent element.
        """
        cdef bint write_declaration
        cdef int is_standalone

        self._assertHasRoot()
        _assertValidNode(self._context_node)
        if compression is None or compression < 0:
            compression = 0

        # C14N serialisation
        if method == 'c14n':
            if encoding is not None:
                raise ValueError("Cannot specify encoding with C14N")
            if xml_declaration:
                raise ValueError("Cannot enable XML declaration in C14N")

            _tofilelikeC14N(file, self._context_node, exclusive, with_comments,
                            compression, inclusive_ns_prefixes)
            return
        if not with_comments:
            raise ValueError("Can only discard comments in C14N serialisation")
        # suppress decl. in default case (purely for ElementTree compatibility)
        if xml_declaration is not None:
            write_declaration = xml_declaration
            if encoding is None:
                encoding = u'ASCII'
            else:
                encoding = encoding.upper()
        elif encoding is None:
            encoding = u'ASCII'
            write_declaration = 0
        else:
            encoding = encoding.upper()
            write_declaration = encoding not in \
                                  (u'US-ASCII', u'ASCII', u'UTF8', u'UTF-8')
        if standalone is None:
            is_standalone = -1
        elif standalone:
            write_declaration = 1
            is_standalone = 1
        else:
            write_declaration = 1
            is_standalone = 0

        if docstring is not None and doctype is None:
            import warnings
            warnings.warn(
                "The 'docstring' option is deprecated. Use 'doctype' instead.",
                DeprecationWarning)
            doctype = docstring

        _tofilelike(file, self._context_node, encoding, doctype, method,
                    write_declaration, 1, pretty_print, with_tail,
                    is_standalone, compression)

    def getpath(self, _Element element not None):
        u"""getpath(self, element)

        Returns a structural, absolute XPath expression to find the element.

        For namespaced elements, the expression uses prefixes from the
        document, which therefore need to be provided in order to make any
        use of the expression in XPath.

        Also see the method getelementpath(self, element), which returns a
        self-contained ElementPath expression.
        """
        cdef _Document doc
        cdef _Element root
        cdef xmlDoc* c_doc
        _assertValidNode(element)
        if self._context_node is not None:
            root = self._context_node
            doc = root._doc
        elif self._doc is not None:
            doc = self._doc
            root = doc.getroot()
        else:
            raise ValueError, u"Element is not in this tree."
        _assertValidDoc(doc)
        _assertValidNode(root)
        if element._doc is not doc:
            raise ValueError, u"Element is not in this tree."

        c_doc = _fakeRootDoc(doc._c_doc, root._c_node)
        c_path = tree.xmlGetNodePath(element._c_node)
        _destroyFakeDoc(doc._c_doc, c_doc)
        if c_path is NULL:
            raise MemoryError()
        path = funicode(c_path)
        tree.xmlFree(c_path)
        return path

    def getelementpath(self, _Element element not None):
        u"""getelementpath(self, element)

        Returns a structural, absolute ElementPath expression to find the
        element.  This path can be used in the .find() method to look up
        the element, provided that the elements along the path and their
        list of immediate children were not modified in between.

        ElementPath has the advantage over an XPath expression (as returned
        by the .getpath() method) that it does not require additional prefix
        declarations.  It is always self-contained.
        """
        cdef _Element root
        cdef Py_ssize_t count
        _assertValidNode(element)
        if element._c_node.type != tree.XML_ELEMENT_NODE:
            raise ValueError, u"input is not an Element"
        if self._context_node is not None:
            root = self._context_node
        elif self._doc is not None:
            root = self._doc.getroot()
        else:
            raise ValueError, u"Element is not in this tree"
        _assertValidNode(root)
        if element._doc is not root._doc:
            raise ValueError, u"Element is not in this tree"

        path = []
        c_element = element._c_node
        while c_element is not root._c_node:
            c_name = c_element.name
            c_href = _getNs(c_element)
            tag = _namespacedNameFromNsName(c_href, c_name)
            if c_href is NULL:
                c_href = <const_xmlChar*>b''  # no namespace (NULL is wildcard)
            # use tag[N] if there are preceding siblings with the same tag
            count = 0
            c_node = c_element.prev
            while c_node is not NULL:
                if c_node.type == tree.XML_ELEMENT_NODE:
                    if _tagMatches(c_node, c_href, c_name):
                        count += 1
                c_node = c_node.prev
            if count:
                tag = '%s[%d]' % (tag, count+1)
            else:
                # use tag[1] if there are following siblings with the same tag
                c_node = c_element.next
                while c_node is not NULL:
                    if c_node.type == tree.XML_ELEMENT_NODE:
                        if _tagMatches(c_node, c_href, c_name):
                            tag += '[1]'
                            break
                    c_node = c_node.next

            path.append(tag)
            c_element = c_element.parent
            if c_element is NULL or c_element.type != tree.XML_ELEMENT_NODE:
                raise ValueError, u"Element is not in this tree."
        if not path:
            return '.'
        path.reverse()
        return '/'.join(path)

    def getiterator(self, tag=None, *tags):
        u"""getiterator(self, *tags, tag=None)

        Returns a sequence or iterator of all elements in document order
        (depth first pre-order), starting with the root element.

        Can be restricted to find only elements with a specific tag,
        see `_Element.iter`.

        :deprecated: Note that this method is deprecated as of
          ElementTree 1.3 and lxml 2.0.  It returns an iterator in
          lxml, which diverges from the original ElementTree
          behaviour.  If you want an efficient iterator, use the
          ``tree.iter()`` method instead.  You should only use this
          method in new code if you require backwards compatibility
          with older versions of lxml or ElementTree.
        """
        root = self.getroot()
        if root is None:
            return ITER_EMPTY
        if tag is not None:
            tags += (tag,)
        return root.getiterator(*tags)

    def iter(self, tag=None, *tags):
        u"""iter(self, tag=None, *tags)

        Creates an iterator for the root element.  The iterator loops over
        all elements in this tree, in document order.  Note that siblings
        of the root element (comments or processing instructions) are not
        returned by the iterator.

        Can be restricted to find only elements with a specific tag,
        see `_Element.iter`.
        """
        root = self.getroot()
        if root is None:
            return ITER_EMPTY
        if tag is not None:
            tags += (tag,)
        return root.iter(*tags)

    def find(self, path, namespaces=None):
        u"""find(self, path, namespaces=None)

        Finds the first toplevel element with given tag.  Same as
        ``tree.getroot().find(path)``.

        The optional ``namespaces`` argument accepts a
        prefix-to-namespace mapping that allows the usage of XPath
        prefixes in the path expression.
        """
        self._assertHasRoot()
        root = self.getroot()
        if _isString(path):
            if path[:1] == "/":
                path = "." + path
        return root.find(path, namespaces)

    def findtext(self, path, default=None, namespaces=None):
        u"""findtext(self, path, default=None, namespaces=None)

        Finds the text for the first element matching the ElementPath
        expression.  Same as getroot().findtext(path)

        The optional ``namespaces`` argument accepts a
        prefix-to-namespace mapping that allows the usage of XPath
        prefixes in the path expression.
        """
        self._assertHasRoot()
        root = self.getroot()
        if _isString(path):
            if path[:1] == "/":
                path = "." + path
        return root.findtext(path, default, namespaces)

    def findall(self, path, namespaces=None):
        u"""findall(self, path, namespaces=None)

        Finds all elements matching the ElementPath expression.  Same as
        getroot().findall(path).

        The optional ``namespaces`` argument accepts a
        prefix-to-namespace mapping that allows the usage of XPath
        prefixes in the path expression.
        """
        self._assertHasRoot()
        root = self.getroot()
        if _isString(path):
            if path[:1] == "/":
                path = "." + path
        return root.findall(path, namespaces)

    def iterfind(self, path, namespaces=None):
        u"""iterfind(self, path, namespaces=None)

        Iterates over all elements matching the ElementPath expression.
        Same as getroot().iterfind(path).

        The optional ``namespaces`` argument accepts a
        prefix-to-namespace mapping that allows the usage of XPath
        prefixes in the path expression.
        """
        self._assertHasRoot()
        root = self.getroot()
        if _isString(path):
            if path[:1] == "/":
                path = "." + path
        return root.iterfind(path, namespaces)

    def xpath(self, _path, *, namespaces=None, extensions=None,
              smart_strings=True, **_variables):
        u"""xpath(self, _path, namespaces=None, extensions=None, smart_strings=True, **_variables)

        XPath evaluate in context of document.

        ``namespaces`` is an optional dictionary with prefix to namespace URI
        mappings, used by XPath.  ``extensions`` defines additional extension
        functions.

        Returns a list (nodeset), or bool, float or string.

        In case of a list result, return Element for element nodes,
        string for text and attribute values.

        Note: if you are going to apply multiple XPath expressions
        against the same document, it is more efficient to use
        XPathEvaluator directly.
        """
        self._assertHasRoot()
        evaluator = XPathDocumentEvaluator(self, namespaces=namespaces,
                                           extensions=extensions,
                                           smart_strings=smart_strings)
        return evaluator(_path, **_variables)

    def xslt(self, _xslt, extensions=None, access_control=None, **_kw):
        u"""xslt(self, _xslt, extensions=None, access_control=None, **_kw)

        Transform this document using other document.

        xslt is a tree that should be XSLT
        keyword parameters are XSLT transformation parameters.

        Returns the transformed tree.

        Note: if you are going to apply the same XSLT stylesheet against
        multiple documents, it is more efficient to use the XSLT
        class directly.
        """
        self._assertHasRoot()
        style = XSLT(_xslt, extensions=extensions,
                     access_control=access_control)
        return style(self, **_kw)

    def relaxng(self, relaxng):
        u"""relaxng(self, relaxng)

        Validate this document using other document.

        The relaxng argument is a tree that should contain a Relax NG schema.

        Returns True or False, depending on whether validation
        succeeded.

        Note: if you are going to apply the same Relax NG schema against
        multiple documents, it is more efficient to use the RelaxNG
        class directly.
        """
        self._assertHasRoot()
        schema = RelaxNG(relaxng)
        return schema.validate(self)

    def xmlschema(self, xmlschema):
        u"""xmlschema(self, xmlschema)

        Validate this document using other document.

        The xmlschema argument is a tree that should contain an XML Schema.

        Returns True or False, depending on whether validation
        succeeded.

        Note: If you are going to apply the same XML Schema against
        multiple documents, it is more efficient to use the XMLSchema
        class directly.
        """
        self._assertHasRoot()
        schema = XMLSchema(xmlschema)
        return schema.validate(self)

    def xinclude(self):
        u"""xinclude(self)

        Process the XInclude nodes in this document and include the
        referenced XML fragments.

        There is support for loading files through the file system, HTTP and
        FTP.

        Note that XInclude does not support custom resolvers in Python space
        due to restrictions of libxml2 <= 2.6.29.
        """
        self._assertHasRoot()
        XInclude()(self._context_node)

    def write_c14n(self, file, *, exclusive=False, with_comments=True,
                   compression=0, inclusive_ns_prefixes=None):
        u"""write_c14n(self, file, exclusive=False, with_comments=True,
                       compression=0, inclusive_ns_prefixes=None)

        C14N write of document. Always writes UTF-8.

        The ``compression`` option enables GZip compression level 1-9.

        The ``inclusive_ns_prefixes`` should be a list of namespace strings
        (i.e. ['xs', 'xsi']) that will be promoted to the top-level element
        during exclusive C14N serialisation.  This parameter is ignored if
        exclusive mode=False.

        If exclusive=True and no list is provided, a namespace will only be
        rendered if it is used by the immediate parent or one of its attributes
        and its prefix and values have not already been rendered by an ancestor
        of the namespace node's parent element.
        """
        self._assertHasRoot()
        _assertValidNode(self._context_node)
        if compression is None or compression < 0:
            compression = 0

        _tofilelikeC14N(file, self._context_node, exclusive, with_comments,
                        compression, inclusive_ns_prefixes)

cdef _ElementTree _elementTreeFactory(_Document doc, _Element context_node):
    return _newElementTree(doc, context_node, _ElementTree)

cdef _ElementTree _newElementTree(_Document doc, _Element context_node,
                                  object baseclass):
    cdef _ElementTree result
    result = baseclass()
    if context_node is None and doc is not None:
        context_node = doc.getroot()
    if context_node is None:
        _assertValidDoc(doc)
        result._doc = doc
    else:
        _assertValidNode(context_node)
    result._context_node = context_node
    return result


@cython.final
@cython.freelist(16)
cdef class _Attrib:
    u"""A dict-like proxy for the ``Element.attrib`` property.
    """
    cdef _Element _element
    def __cinit__(self, _Element element not None):
        _assertValidNode(element)
        self._element = element

    # MANIPULATORS
    def __setitem__(self, key, value):
        _assertValidNode(self._element)
        _setAttributeValue(self._element, key, value)

    def __delitem__(self, key):
        _assertValidNode(self._element)
        _delAttribute(self._element, key)

    def update(self, sequence_or_dict):
        _assertValidNode(self._element)
        if isinstance(sequence_or_dict, (dict, _Attrib)):
            sequence_or_dict = sequence_or_dict.items()
        for key, value in sequence_or_dict:
            _setAttributeValue(self._element, key, value)

    def pop(self, key, *default):
        if len(default) > 1:
            raise TypeError, u"pop expected at most 2 arguments, got %d" % (
                len(default)+1)
        _assertValidNode(self._element)
        result = _getAttributeValue(self._element, key, None)
        if result is None:
            if not default:
                raise KeyError, key
            result = default[0]
        else:
            _delAttribute(self._element, key)
        return result

    def clear(self):
        _assertValidNode(self._element)
        cdef xmlNode* c_node = self._element._c_node
        while c_node.properties is not NULL:
            tree.xmlRemoveProp(c_node.properties)

    # ACCESSORS
    def __repr__(self):
        _assertValidNode(self._element)
        return repr(dict( _collectAttributes(self._element._c_node, 3) ))

    def __copy__(self):
        _assertValidNode(self._element)
        return dict(_collectAttributes(self._element._c_node, 3))

    def __deepcopy__(self, memo):
        _assertValidNode(self._element)
        return dict(_collectAttributes(self._element._c_node, 3))

    def __getitem__(self, key):
        _assertValidNode(self._element)
        result = _getAttributeValue(self._element, key, None)
        if result is None:
            raise KeyError, key
        return result

    def __bool__(self):
        _assertValidNode(self._element)
        cdef xmlAttr* c_attr = self._element._c_node.properties
        while c_attr is not NULL:
            if c_attr.type == tree.XML_ATTRIBUTE_NODE:
                return 1
            c_attr = c_attr.next
        return 0

    def __len__(self):
        _assertValidNode(self._element)
        cdef xmlAttr* c_attr = self._element._c_node.properties
        cdef Py_ssize_t c = 0
        while c_attr is not NULL:
            if c_attr.type == tree.XML_ATTRIBUTE_NODE:
                c += 1
            c_attr = c_attr.next
        return c

    def get(self, key, default=None):
        _assertValidNode(self._element)
        return _getAttributeValue(self._element, key, default)

    def keys(self):
        _assertValidNode(self._element)
        return _collectAttributes(self._element._c_node, 1)

    def __iter__(self):
        _assertValidNode(self._element)
        return iter(_collectAttributes(self._element._c_node, 1))

    def iterkeys(self):
        _assertValidNode(self._element)
        return iter(_collectAttributes(self._element._c_node, 1))

    def values(self):
        _assertValidNode(self._element)
        return _collectAttributes(self._element._c_node, 2)

    def itervalues(self):
        _assertValidNode(self._element)
        return iter(_collectAttributes(self._element._c_node, 2))

    def items(self):
        _assertValidNode(self._element)
        return _collectAttributes(self._element._c_node, 3)

    def iteritems(self):
        _assertValidNode(self._element)
        return iter(_collectAttributes(self._element._c_node, 3))

    def has_key(self, key):
        _assertValidNode(self._element)
        return key in self

    def __contains__(self, key):
        _assertValidNode(self._element)
        cdef xmlNode* c_node
        ns, tag = _getNsTag(key)
        c_node = self._element._c_node
        c_href = <const_xmlChar*>NULL if ns is None else _xcstr(ns)
        return 1 if tree.xmlHasNsProp(c_node, _xcstr(tag), c_href) else 0

    def __richcmp__(one, other, int op):
        try:
            if not isinstance(one, dict):
                one = dict(one)
            if not isinstance(other, dict):
                other = dict(other)
        except (TypeError, ValueError):
            return NotImplemented
        return python.PyObject_RichCompare(one, other, op)


@cython.final
@cython.internal
cdef class _AttribIterator:
    u"""Attribute iterator - for internal use only!
    """
    # XML attributes must not be removed while running!
    cdef _Element _node
    cdef xmlAttr* _c_attr
    cdef int _keysvalues # 1 - keys, 2 - values, 3 - items (key, value)
    def __iter__(self):
        return self

    def __next__(self):
        cdef xmlAttr* c_attr
        if self._node is None:
            raise StopIteration
        c_attr = self._c_attr
        while c_attr is not NULL and c_attr.type != tree.XML_ATTRIBUTE_NODE:
            c_attr = c_attr.next
        if c_attr is NULL:
            self._node = None
            raise StopIteration

        self._c_attr = c_attr.next
        if self._keysvalues == 1:
            return _namespacedName(<xmlNode*>c_attr)
        elif self._keysvalues == 2:
            return _attributeValue(self._node._c_node, c_attr)
        else:
            return (_namespacedName(<xmlNode*>c_attr),
                    _attributeValue(self._node._c_node, c_attr))

cdef object _attributeIteratorFactory(_Element element, int keysvalues):
    cdef _AttribIterator attribs
    if element._c_node.properties is NULL:
        return ITER_EMPTY
    attribs = _AttribIterator()
    attribs._node = element
    attribs._c_attr = element._c_node.properties
    attribs._keysvalues = keysvalues
    return attribs


cdef public class _ElementTagMatcher [ object LxmlElementTagMatcher,
                                       type LxmlElementTagMatcherType ]:
    """
    Dead but public. :)
    """
    cdef object _pystrings
    cdef int _node_type
    cdef char* _href
    cdef char* _name
    cdef _initTagMatch(self, tag):
        self._href = NULL
        self._name = NULL
        if tag is None:
            self._node_type = 0
        elif tag is Comment:
            self._node_type = tree.XML_COMMENT_NODE
        elif tag is ProcessingInstruction:
            self._node_type = tree.XML_PI_NODE
        elif tag is Entity:
            self._node_type = tree.XML_ENTITY_REF_NODE
        elif tag is Element:
            self._node_type = tree.XML_ELEMENT_NODE
        else:
            self._node_type = tree.XML_ELEMENT_NODE
            self._pystrings = _getNsTag(tag)
            if self._pystrings[0] is not None:
                self._href = _cstr(self._pystrings[0])
            self._name = _cstr(self._pystrings[1])
            if self._name[0] == c'*' and self._name[1] == c'\0':
                self._name = NULL

cdef public class _ElementIterator(_ElementTagMatcher) [
    object LxmlElementIterator, type LxmlElementIteratorType ]:
    """
    Dead but public. :)
    """
    # we keep Python references here to control GC
    cdef _Element _node
    cdef _node_to_node_function _next_element
    def __iter__(self):
        return self

    cdef void _storeNext(self, _Element node):
        cdef xmlNode* c_node
        c_node = self._next_element(node._c_node)
        while c_node is not NULL and \
                  self._node_type != 0 and \
                  (<tree.xmlElementType>self._node_type != c_node.type or
                   not _tagMatches(c_node, <const_xmlChar*>self._href, <const_xmlChar*>self._name)):
            c_node = self._next_element(c_node)
        if c_node is NULL:
            self._node = None
        else:
            # Python ref:
            self._node = _elementFactory(node._doc, c_node)

    def __next__(self):
        cdef xmlNode* c_node
        cdef _Element current_node
        if self._node is None:
            raise StopIteration
        # Python ref:
        current_node = self._node
        self._storeNext(current_node)
        return current_node

@cython.final
@cython.internal
cdef class _MultiTagMatcher:
    """
    Match an xmlNode against a list of tags.
    """
    cdef list _py_tags
    cdef qname* _cached_tags
    cdef size_t _tag_count
    cdef size_t _cached_size
    cdef _Document _cached_doc
    cdef int _node_types

    def __cinit__(self, tags):
        self._cached_tags = NULL
        self._cached_size = 0
        self._tag_count = 0
        self._node_types = 0
        self._py_tags = []
        self.initTagMatch(tags)

    def __dealloc__(self):
        self._clear()

    cdef bint rejectsAll(self):
        return not self._tag_count and not self._node_types

    cdef bint rejectsAllAttributes(self):
        return not self._tag_count

    cdef bint matchesType(self, int node_type):
        if node_type == tree.XML_ELEMENT_NODE and self._tag_count:
            return True
        return self._node_types & (1 << node_type)

    cdef void _clear(self):
        cdef size_t i, count
        count = self._tag_count
        self._tag_count = 0
        if self._cached_tags:
            for i in xrange(count):
                cpython.ref.Py_XDECREF(self._cached_tags[i].href)
            python.lxml_free(self._cached_tags)
            self._cached_tags = NULL

    cdef initTagMatch(self, tags):
        self._cached_doc = None
        del self._py_tags[:]
        self._clear()
        if tags is None or tags == ():
            # no selection in tags argument => match anything
            self._node_types = (
                1 << tree.XML_COMMENT_NODE |
                1 << tree.XML_PI_NODE |
                1 << tree.XML_ENTITY_REF_NODE |
                1 << tree.XML_ELEMENT_NODE)
        else:
            self._node_types = 0
            self._storeTags(tags, set())

    cdef _storeTags(self, tag, set seen):
        if tag is Comment:
            self._node_types |= 1 << tree.XML_COMMENT_NODE
        elif tag is ProcessingInstruction:
            self._node_types |= 1 << tree.XML_PI_NODE
        elif tag is Entity:
            self._node_types |= 1 << tree.XML_ENTITY_REF_NODE
        elif tag is Element:
            self._node_types |= 1 << tree.XML_ELEMENT_NODE
        elif python._isString(tag):
            if tag in seen:
                return
            seen.add(tag)
            if tag in ('*', '{*}*'):
                self._node_types |= 1 << tree.XML_ELEMENT_NODE
            else:
                href, name = _getNsTag(tag)
                if name == b'*':
                    name = None
                if href is None:
                    href = b''  # no namespace
                elif href == b'*':
                    href = None  # wildcard: any namespace, including none
                self._py_tags.append((href, name))
        else:
            # support a sequence of tags
            for item in tag:
                self._storeTags(item, seen)

    cdef inline int cacheTags(self, _Document doc, bint force_into_dict=False) except -1:
        """
        Look up the tag names in the doc dict to enable string pointer comparisons.
        """
        cdef size_t dict_size = tree.xmlDictSize(doc._c_doc.dict)
        if doc is self._cached_doc and dict_size == self._cached_size:
            # doc and dict didn't change => names already cached
            return 0
        self._tag_count = 0
        if not self._py_tags:
            self._cached_doc = doc
            self._cached_size = dict_size
            return 0
        if not self._cached_tags:
            self._cached_tags = <qname*>python.lxml_malloc(len(self._py_tags), sizeof(qname))
            if not self._cached_tags:
                self._cached_doc = None
                raise MemoryError()
        self._tag_count = <size_t>_mapTagsToQnameMatchArray(
            doc._c_doc, self._py_tags, self._cached_tags, force_into_dict)
        self._cached_doc = doc
        self._cached_size = dict_size
        return 0

    cdef inline bint matches(self, xmlNode* c_node):
        cdef qname* c_qname
        if self._node_types & (1 << c_node.type):
            return True
        elif c_node.type == tree.XML_ELEMENT_NODE:
            for c_qname in self._cached_tags[:self._tag_count]:
                if _tagMatchesExactly(c_node, c_qname):
                    return True
        return False

    cdef inline bint matchesNsTag(self, const_xmlChar* c_href,
                                  const_xmlChar* c_name):
        cdef qname* c_qname
        if self._node_types & (1 << tree.XML_ELEMENT_NODE):
            return True
        for c_qname in self._cached_tags[:self._tag_count]:
            if _nsTagMatchesExactly(c_href, c_name, c_qname):
                return True
        return False

    cdef inline bint matchesAttribute(self, xmlAttr* c_attr):
        """Attribute matches differ from Element matches in that they do
        not care about node types.
        """
        cdef qname* c_qname
        for c_qname in self._cached_tags[:self._tag_count]:
            if _tagMatchesExactly(<xmlNode*>c_attr, c_qname):
                return True
        return False

cdef class _ElementMatchIterator:
    cdef _Element _node
    cdef _node_to_node_function _next_element
    cdef _MultiTagMatcher _matcher

    @cython.final
    cdef _initTagMatcher(self, tags):
        self._matcher = _MultiTagMatcher(tags)

    def __iter__(self):
        return self

    @cython.final
    cdef int _storeNext(self, _Element node) except -1:
        self._matcher.cacheTags(node._doc)
        c_node = self._next_element(node._c_node)
        while c_node is not NULL and not self._matcher.matches(c_node):
            c_node = self._next_element(c_node)
        # store Python ref to next node to make sure it's kept alive
        self._node = _elementFactory(node._doc, c_node) if c_node is not NULL else None
        return 0

    def __next__(self):
        cdef _Element current_node = self._node
        if current_node is None:
            raise StopIteration
        self._storeNext(current_node)
        return current_node

cdef class ElementChildIterator(_ElementMatchIterator):
    u"""ElementChildIterator(self, node, tag=None, reversed=False)
    Iterates over the children of an element.
    """
    def __cinit__(self, _Element node not None, tag=None, *, bint reversed=False):
        cdef xmlNode* c_node
        _assertValidNode(node)
        self._initTagMatcher(tag)
        if reversed:
            c_node = _findChildBackwards(node._c_node, 0)
            self._next_element = _previousElement
        else:
            c_node = _findChildForwards(node._c_node, 0)
            self._next_element = _nextElement
        self._matcher.cacheTags(node._doc)
        while c_node is not NULL and not self._matcher.matches(c_node):
            c_node = self._next_element(c_node)
        # store Python ref to next node to make sure it's kept alive
        self._node = _elementFactory(node._doc, c_node) if c_node is not NULL else None

cdef class SiblingsIterator(_ElementMatchIterator):
    u"""SiblingsIterator(self, node, tag=None, preceding=False)
    Iterates over the siblings of an element.

    You can pass the boolean keyword ``preceding`` to specify the direction.
    """
    def __cinit__(self, _Element node not None, tag=None, *, bint preceding=False):
        _assertValidNode(node)
        self._initTagMatcher(tag)
        if preceding:
            self._next_element = _previousElement
        else:
            self._next_element = _nextElement
        self._storeNext(node)

cdef class AncestorsIterator(_ElementMatchIterator):
    u"""AncestorsIterator(self, node, tag=None)
    Iterates over the ancestors of an element (from parent to parent).
    """
    def __cinit__(self, _Element node not None, tag=None):
        _assertValidNode(node)
        self._initTagMatcher(tag)
        self._next_element = _parentElement
        self._storeNext(node)

cdef class ElementDepthFirstIterator:
    u"""ElementDepthFirstIterator(self, node, tag=None, inclusive=True)
    Iterates over an element and its sub-elements in document order (depth
    first pre-order).

    Note that this also includes comments, entities and processing
    instructions.  To filter them out, check if the ``tag`` property
    of the returned element is a string (i.e. not None and not a
    factory function), or pass the ``Element`` factory for the ``tag``
    argument to receive only Elements.

    If the optional ``tag`` argument is not None, the iterator returns only
    the elements that match the respective name and namespace.

    The optional boolean argument 'inclusive' defaults to True and can be set
    to False to exclude the start element itself.

    Note that the behaviour of this iterator is completely undefined if the
    tree it traverses is modified during iteration.
    """
    # we keep Python references here to control GC
    # keep the next Element after the one we return, and the (s)top node
    cdef _Element _next_node
    cdef _Element _top_node
    cdef _MultiTagMatcher _matcher
    def __cinit__(self, _Element node not None, tag=None, *, bint inclusive=True):
        _assertValidNode(node)
        self._top_node  = node
        self._next_node = node
        self._matcher = _MultiTagMatcher(tag)
        self._matcher.cacheTags(node._doc)
        if not inclusive or not self._matcher.matches(node._c_node):
            # find start node (this cannot raise StopIteration, self._next_node != None)
            next(self)

    def __iter__(self):
        return self

    def __next__(self):
        cdef xmlNode* c_node
        cdef _Element current_node = self._next_node
        if current_node is None:
            raise StopIteration
        c_node = current_node._c_node
        self._matcher.cacheTags(current_node._doc)
        if not self._matcher._tag_count:
            # no tag name was found in the dict => not in document either
            # try to match by node type
            c_node = self._nextNodeAnyTag(c_node)
        else:
            c_node = self._nextNodeMatchTag(c_node)
        if c_node is NULL:
            self._next_node = None
        else:
            self._next_node = _elementFactory(current_node._doc, c_node)
        return current_node

    @cython.final
    cdef xmlNode* _nextNodeAnyTag(self, xmlNode* c_node):
        cdef int node_types = self._matcher._node_types
        if not node_types:
            return NULL
        tree.BEGIN_FOR_EACH_ELEMENT_FROM(self._top_node._c_node, c_node, 0)
        if node_types & (1 << c_node.type):
            return c_node
        tree.END_FOR_EACH_ELEMENT_FROM(c_node)
        return NULL

    @cython.final
    cdef xmlNode* _nextNodeMatchTag(self, xmlNode* c_node):
        tree.BEGIN_FOR_EACH_ELEMENT_FROM(self._top_node._c_node, c_node, 0)
        if self._matcher.matches(c_node):
            return c_node
        tree.END_FOR_EACH_ELEMENT_FROM(c_node)
        return NULL

cdef class ElementTextIterator:
    u"""ElementTextIterator(self, element, tag=None, with_tail=True)
    Iterates over the text content of a subtree.

    You can pass the ``tag`` keyword argument to restrict text content to a
    specific tag name.

    You can set the ``with_tail`` keyword argument to ``False`` to skip over
    tail text (e.g. if you know that it's only whitespace from pretty-printing).
    """
    cdef object _nextEvent
    cdef _Element _start_element
    def __cinit__(self, _Element element not None, tag=None, *, bint with_tail=True):
        _assertValidNode(element)
        if with_tail:
            events = (u"start", u"end")
        else:
            events = (u"start",)
        self._start_element = element
        self._nextEvent = iterwalk(element, events=events, tag=tag).__next__

    def __iter__(self):
        return self

    def __next__(self):
        cdef _Element element
        result = None
        while result is None:
            event, element = self._nextEvent() # raises StopIteration
            if event == u"start":
                result = element.text
            elif element is not self._start_element:
                result = element.tail
        return result

cdef xmlNode* _createElement(xmlDoc* c_doc, object name_utf) except NULL:
    cdef xmlNode* c_node
    c_node = tree.xmlNewDocNode(c_doc, NULL, _xcstr(name_utf), NULL)
    return c_node

cdef xmlNode* _createComment(xmlDoc* c_doc, const_xmlChar* text):
    cdef xmlNode* c_node
    c_node = tree.xmlNewDocComment(c_doc, text)
    return c_node

cdef xmlNode* _createPI(xmlDoc* c_doc, const_xmlChar* target, const_xmlChar* text):
    cdef xmlNode* c_node
    c_node = tree.xmlNewDocPI(c_doc, target, text)
    return c_node

cdef xmlNode* _createEntity(xmlDoc* c_doc, const_xmlChar* name):
    cdef xmlNode* c_node
    c_node = tree.xmlNewReference(c_doc, name)
    return c_node

# module-level API for ElementTree

def Element(_tag, attrib=None, nsmap=None, **_extra):
    u"""Element(_tag, attrib=None, nsmap=None, **_extra)

    Element factory.  This function returns an object implementing the
    Element interface.

    Also look at the `_Element.makeelement()` and
    `_BaseParser.makeelement()` methods, which provide a faster way to
    create an Element within a specific document or parser context.
    """
    return _makeElement(_tag, NULL, None, None, None, None,
                        attrib, nsmap, _extra)


def Comment(text=None):
    u"""Comment(text=None)

    Comment element factory. This factory function creates a special element that will
    be serialized as an XML comment.
    """
    cdef _Document doc
    cdef xmlNode*  c_node
    cdef xmlDoc*   c_doc

    if text is None:
        text = b''
    else:
        text = _utf8(text)
        if b'--' in text or text.endswith(b'-'):
            raise ValueError("Comment may not contain '--' or end with '-'")

    c_doc = _newXMLDoc()
    doc = _documentFactory(c_doc, None)
    c_node = _createComment(c_doc, _xcstr(text))
    tree.xmlAddChild(<xmlNode*>c_doc, c_node)
    return _elementFactory(doc, c_node)


def ProcessingInstruction(target, text=None):
    u"""ProcessingInstruction(target, text=None)

    ProcessingInstruction element factory. This factory function creates a
    special element that will be serialized as an XML processing instruction.
    """
    cdef _Document doc
    cdef xmlNode*  c_node
    cdef xmlDoc*   c_doc

    target = _utf8(target)
    _tagValidOrRaise(target)
    if target.lower() == b'xml':
        raise ValueError("Invalid PI name '%s'" % target)

    if text is None:
        text = b''
    else:
        text = _utf8(text)
        if b'?>' in text:
            raise ValueError("PI text must not contain '?>'")

    c_doc = _newXMLDoc()
    doc = _documentFactory(c_doc, None)
    c_node = _createPI(c_doc, _xcstr(target), _xcstr(text))
    tree.xmlAddChild(<xmlNode*>c_doc, c_node)
    return _elementFactory(doc, c_node)

PI = ProcessingInstruction


cdef class CDATA:
    u"""CDATA(data)

    CDATA factory.  This factory creates an opaque data object that
    can be used to set Element text.  The usual way to use it is::

        >>> el = Element('content')
        >>> el.text = CDATA('a string')

        >>> print(el.text)
        a string
        >>> print(tostring(el, encoding="unicode"))
        <content><![CDATA[a string]]></content>
    """
    cdef bytes _utf8_data
    def __cinit__(self, data):
        _utf8_data = _utf8(data)
        if b']]>' in _utf8_data:
            raise ValueError("']]>' not allowed inside CDATA")
        self._utf8_data = _utf8_data


def Entity(name):
    u"""Entity(name)

    Entity factory.  This factory function creates a special element
    that will be serialized as an XML entity reference or character
    reference.  Note, however, that entities will not be automatically
    declared in the document.  A document that uses entity references
    requires a DTD to define the entities.
    """
    cdef _Document doc
    cdef xmlNode*  c_node
    cdef xmlDoc*   c_doc
    name_utf = _utf8(name)
    c_name = _xcstr(name_utf)
    if c_name[0] == c'#':
        if not _characterReferenceIsValid(c_name + 1):
            raise ValueError, u"Invalid character reference: '%s'" % name
    elif not _xmlNameIsValid(c_name):
        raise ValueError, u"Invalid entity reference: '%s'" % name
    c_doc = _newXMLDoc()
    doc = _documentFactory(c_doc, None)
    c_node = _createEntity(c_doc, c_name)
    tree.xmlAddChild(<xmlNode*>c_doc, c_node)
    return _elementFactory(doc, c_node)


def SubElement(_Element _parent not None, _tag,
               attrib=None, nsmap=None, **_extra):
    u"""SubElement(_parent, _tag, attrib=None, nsmap=None, **_extra)

    Subelement factory.  This function creates an element instance, and
    appends it to an existing element.
    """
    return _makeSubElement(_parent, _tag, None, None, attrib, nsmap, _extra)


def ElementTree(_Element element=None, *, file=None, _BaseParser parser=None):
    u"""ElementTree(element=None, file=None, parser=None)

    ElementTree wrapper class.
    """
    cdef xmlNode* c_next
    cdef xmlNode* c_node
    cdef xmlNode* c_node_copy
    cdef xmlDoc*  c_doc
    cdef _ElementTree etree
    cdef _Document doc

    if element is not None:
        doc  = element._doc
    elif file is not None:
        try:
            doc = _parseDocument(file, parser, None)
        except _TargetParserResult as result_container:
            return result_container.result
    else:
        c_doc = _newXMLDoc()
        doc = _documentFactory(c_doc, parser)

    return _elementTreeFactory(doc, element)


def HTML(text, _BaseParser parser=None, *, base_url=None):
    u"""HTML(text, parser=None, base_url=None)

    Parses an HTML document from a string constant.  Returns the root
    node (or the result returned by a parser target).  This function
    can be used to embed "HTML literals" in Python code.

    To override the parser with a different ``HTMLParser`` you can pass it to
    the ``parser`` keyword argument.

    The ``base_url`` keyword argument allows to set the original base URL of
    the document to support relative Paths when looking up external entities
    (DTD, XInclude, ...).
    """
    cdef _Document doc
    if parser is None:
        parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
        if not isinstance(parser, HTMLParser):
            parser = __DEFAULT_HTML_PARSER
    try:
        doc = _parseMemoryDocument(text, base_url, parser)
        return doc.getroot()
    except _TargetParserResult as result_container:
        return result_container.result


def XML(text, _BaseParser parser=None, *, base_url=None):
    u"""XML(text, parser=None, base_url=None)

    Parses an XML document or fragment from a string constant.
    Returns the root node (or the result returned by a parser target).
    This function can be used to embed "XML literals" in Python code,
    like in

       >>> root = XML("<root><test/></root>")
       >>> print(root.tag)
       root

    To override the parser with a different ``XMLParser`` you can pass it to
    the ``parser`` keyword argument.

    The ``base_url`` keyword argument allows to set the original base URL of
    the document to support relative Paths when looking up external entities
    (DTD, XInclude, ...).
    """
    cdef _Document doc
    if parser is None:
        parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
        if not isinstance(parser, XMLParser):
            parser = __DEFAULT_XML_PARSER
    try:
        doc = _parseMemoryDocument(text, base_url, parser)
        return doc.getroot()
    except _TargetParserResult as result_container:
        return result_container.result


def fromstring(text, _BaseParser parser=None, *, base_url=None):
    u"""fromstring(text, parser=None, base_url=None)

    Parses an XML document or fragment from a string.  Returns the
    root node (or the result returned by a parser target).

    To override the default parser with a different parser you can pass it to
    the ``parser`` keyword argument.

    The ``base_url`` keyword argument allows to set the original base URL of
    the document to support relative Paths when looking up external entities
    (DTD, XInclude, ...).
    """
    cdef _Document doc
    try:
        doc = _parseMemoryDocument(text, base_url, parser)
        return doc.getroot()
    except _TargetParserResult as result_container:
        return result_container.result


def fromstringlist(strings, _BaseParser parser=None):
    u"""fromstringlist(strings, parser=None)

    Parses an XML document from a sequence of strings.  Returns the
    root node (or the result returned by a parser target).

    To override the default parser with a different parser you can pass it to
    the ``parser`` keyword argument.
    """
    cdef _Document doc
    if isinstance(strings, (bytes, unicode)):
        raise ValueError("passing a single string into fromstringlist() is not"
                         " efficient, use fromstring() instead")
    if parser is None:
        parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
    feed = parser.feed
    for data in strings:
        feed(data)
    return parser.close()


def iselement(element):
    u"""iselement(element)

    Checks if an object appears to be a valid element object.
    """
    return isinstance(element, _Element) and (<_Element>element)._c_node is not NULL


def dump(_Element elem not None, *, bint pretty_print=True, with_tail=True):
    u"""dump(elem, pretty_print=True, with_tail=True)

    Writes an element tree or element structure to sys.stdout. This function
    should be used for debugging only.
    """
    xml = tostring(elem, pretty_print=pretty_print, with_tail=with_tail,
                   encoding=None if python.IS_PYTHON2 else 'unicode')
    if not pretty_print:
        xml += '\n'
    sys.stdout.write(xml)


def tostring(element_or_tree, *, encoding=None, method="xml",
             xml_declaration=None, bint pretty_print=False, bint with_tail=True,
             standalone=None, doctype=None,
             bint exclusive=False, bint with_comments=True, inclusive_ns_prefixes=None):
    u"""tostring(element_or_tree, encoding=None, method="xml",
                 xml_declaration=None, pretty_print=False, with_tail=True,
                 standalone=None, doctype=None,
                 exclusive=False, with_comments=True, inclusive_ns_prefixes=None)

    Serialize an element to an encoded string representation of its XML
    tree.

    Defaults to ASCII encoding without XML declaration.  This
    behaviour can be configured with the keyword arguments 'encoding'
    (string) and 'xml_declaration' (bool).  Note that changing the
    encoding to a non UTF-8 compatible encoding will enable a
    declaration by default.

    You can also serialise to a Unicode string without declaration by
    passing the ``unicode`` function as encoding (or ``str`` in Py3),
    or the name 'unicode'.  This changes the return value from a byte
    string to an unencoded unicode string.

    The keyword argument 'pretty_print' (bool) enables formatted XML.

    The keyword argument 'method' selects the output method: 'xml',
    'html', plain 'text' (text content without tags) or 'c14n'.
    Default is 'xml'.

    The ``exclusive`` and ``with_comments`` arguments are only used
    with C14N output, where they request exclusive and uncommented
    C14N serialisation respectively.

    Passing a boolean value to the ``standalone`` option will output
    an XML declaration with the corresponding ``standalone`` flag.

    The ``doctype`` option allows passing in a plain string that will
    be serialised before the XML tree.  Note that passing in non
    well-formed content here will make the XML output non well-formed.
    Also, an existing doctype in the document tree will not be removed
    when serialising an ElementTree instance.

    You can prevent the tail text of the element from being serialised
    by passing the boolean ``with_tail`` option.  This has no impact
    on the tail text of children, which will always be serialised.
    """
    cdef bint write_declaration
    cdef int is_standalone
    # C14N serialisation
    if method == 'c14n':
        if encoding is not None:
            raise ValueError("Cannot specify encoding with C14N")
        if xml_declaration:
            raise ValueError("Cannot enable XML declaration in C14N")
        return _tostringC14N(element_or_tree, exclusive, with_comments, inclusive_ns_prefixes)
    if not with_comments:
        raise ValueError("Can only discard comments in C14N serialisation")
    if encoding is _unicode or (encoding is not None and encoding.lower() == 'unicode'):
        if xml_declaration:
            raise ValueError, \
                u"Serialisation to unicode must not request an XML declaration"
        write_declaration = 0
        encoding = _unicode
    elif xml_declaration is None:
        # by default, write an XML declaration only for non-standard encodings
        write_declaration = encoding is not None and encoding.upper() not in \
                            (u'ASCII', u'UTF-8', u'UTF8', u'US-ASCII')
    else:
        write_declaration = xml_declaration
    if encoding is None:
        encoding = u'ASCII'
    if standalone is None:
        is_standalone = -1
    elif standalone:
        write_declaration = 1
        is_standalone = 1
    else:
        write_declaration = 1
        is_standalone = 0

    if isinstance(element_or_tree, _Element):
        return _tostring(<_Element>element_or_tree, encoding, doctype, method,
                         write_declaration, 0, pretty_print, with_tail,
                         is_standalone)
    elif isinstance(element_or_tree, _ElementTree):
        return _tostring((<_ElementTree>element_or_tree)._context_node,
                         encoding, doctype, method, write_declaration, 1,
                         pretty_print, with_tail, is_standalone)
    else:
        raise TypeError, u"Type '%s' cannot be serialized." % \
            python._fqtypename(element_or_tree).decode('utf8')


def tostringlist(element_or_tree, *args, **kwargs):
    u"""tostringlist(element_or_tree, *args, **kwargs)

    Serialize an element to an encoded string representation of its XML
    tree, stored in a list of partial strings.

    This is purely for ElementTree 1.3 compatibility.  The result is a
    single string wrapped in a list.
    """
    return [tostring(element_or_tree, *args, **kwargs)]


def tounicode(element_or_tree, *, method=u"xml", bint pretty_print=False,
              bint with_tail=True, doctype=None):
    u"""tounicode(element_or_tree, method="xml", pretty_print=False,
                  with_tail=True, doctype=None)

    Serialize an element to the Python unicode representation of its XML
    tree.

    :deprecated: use ``tostring(el, encoding='unicode')`` instead.

    Note that the result does not carry an XML encoding declaration and is
    therefore not necessarily suited for serialization to byte streams without
    further treatment.

    The boolean keyword argument 'pretty_print' enables formatted XML.

    The keyword argument 'method' selects the output method: 'xml',
    'html' or plain 'text'.

    You can prevent the tail text of the element from being serialised
    by passing the boolean ``with_tail`` option.  This has no impact
    on the tail text of children, which will always be serialised.
    """
    if isinstance(element_or_tree, _Element):
        return _tostring(<_Element>element_or_tree, _unicode, doctype, method,
                          0, 0, pretty_print, with_tail, -1)
    elif isinstance(element_or_tree, _ElementTree):
        return _tostring((<_ElementTree>element_or_tree)._context_node,
                         _unicode, doctype, method, 0, 1, pretty_print,
                         with_tail, -1)
    else:
        raise TypeError, u"Type '%s' cannot be serialized." % \
            type(element_or_tree)


def parse(source, _BaseParser parser=None, *, base_url=None):
    u"""parse(source, parser=None, base_url=None)

    Return an ElementTree object loaded with source elements.  If no parser
    is provided as second argument, the default parser is used.

    The ``source`` can be any of the following:

    - a file name/path
    - a file object
    - a file-like object
    - a URL using the HTTP or FTP protocol

    To parse from a string, use the ``fromstring()`` function instead.

    Note that it is generally faster to parse from a file path or URL
    than from an open file object or file-like object.  Transparent
    decompression from gzip compressed sources is supported (unless
    explicitly disabled in libxml2).

    The ``base_url`` keyword allows setting a URL for the document
    when parsing from a file-like object.  This is needed when looking
    up external entities (DTD, XInclude, ...) with relative paths.
    """
    cdef _Document doc
    try:
        doc = _parseDocument(source, parser, base_url)
        return _elementTreeFactory(doc, None)
    except _TargetParserResult as result_container:
        return result_container.result


################################################################################
# Include submodules

include "readonlytree.pxi" # Read-only implementation of Element proxies
include "classlookup.pxi"  # Element class lookup mechanisms
include "nsclasses.pxi"    # Namespace implementation and registry
include "docloader.pxi"    # Support for custom document loaders
include "parser.pxi"       # XML and HTML parsers
include "saxparser.pxi"    # SAX-like Parser interface and tree builder
include "parsertarget.pxi" # ET Parser target
include "serializer.pxi"   # XML output functions
include "iterparse.pxi"    # incremental XML parsing
include "xmlid.pxi"        # XMLID and IDDict
include "xinclude.pxi"     # XInclude
include "cleanup.pxi"      # Cleanup and recursive element removal functions


################################################################################
# Include submodules for XPath and XSLT

include "extensions.pxi"   # XPath/XSLT extension functions
include "xpath.pxi"        # XPath evaluation
include "xslt.pxi"         # XSL transformations
include "xsltext.pxi"      # XSL extension elements


################################################################################
# Validation

class DocumentInvalid(LxmlError):
    u"""Validation error.

    Raised by all document validators when their ``assertValid(tree)``
    method fails.
    """
    pass

cdef class _Validator:
    u"Base class for XML validators."
    cdef _ErrorLog _error_log
    def __cinit__(self):
        self._error_log = _ErrorLog()

    def validate(self, etree):
        u"""validate(self, etree)

        Validate the document using this schema.

        Returns true if document is valid, false if not.
        """
        return self(etree)

    def assertValid(self, etree):
        u"""assertValid(self, etree)

        Raises `DocumentInvalid` if the document does not comply with the schema.
        """
        if not self(etree):
            raise DocumentInvalid(self._error_log._buildExceptionMessage(
                    u"Document does not comply with schema"),
                                  self._error_log)

    def assert_(self, etree):
        u"""assert_(self, etree)

        Raises `AssertionError` if the document does not comply with the schema.
        """
        if not self(etree):
            raise AssertionError, self._error_log._buildExceptionMessage(
                u"Document does not comply with schema")

    cpdef _append_log_message(self, int domain, int type, int level, int line,
                              message, filename):
        self._error_log._receiveGeneric(domain, type, level, line, message,
                                        filename)

    cpdef _clear_error_log(self):
        self._error_log.clear()

    property error_log:
        u"The log of validation errors and warnings."
        def __get__(self):
            assert self._error_log is not None, "XPath evaluator not initialised"
            return self._error_log.copy()

include "dtd.pxi"        # DTD
include "relaxng.pxi"    # RelaxNG
include "xmlschema.pxi"  # XMLSchema
include "schematron.pxi" # Schematron (requires libxml2 2.6.21+)

################################################################################
# Public C API

include "public-api.pxi"

################################################################################
# Other stuff

include "debug.pxi"