File: XmlParser.java

package info (click to toggle)
jedit 4.3.2%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 12,288 kB
  • ctags: 10,215
  • sloc: java: 88,754; xml: 81,655; makefile: 53; sh: 26
file content (4377 lines) | stat: -rw-r--r-- 115,831 bytes parent folder | download
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
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
// XmlParser.java: the main parser class.
// NO WARRANTY! See README, and copyright below.
// $Id: XmlParser.java 14583 2009-02-06 05:38:53Z ezust $

package com.microstar.xml;

import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.InputStream;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Stack;


/**
  * Parse XML documents and return parse events through call-backs.
  * <p>You need to define a class implementing the <code>XmlHandler</code>
  * interface: an object belonging to this class will receive the
  * callbacks for the events.  (As an alternative to implementing
  * the full XmlHandler interface, you can simply extend the 
  * <code>HandlerBase</code> convenience class.)
  * <p>Usage (assuming that <code>MyHandler</code> is your implementation
  * of the <code>XmlHandler</code> interface):
  * <pre>
  * XmlHandler handler = new MyHandler();
  * XmlParser parser = new XmlParser();
  * parser.setHandler(handler);
  * try {
  *   parser.parse("http://www.host.com/doc.xml", null);
  * } catch (Exception e) {
  *   [do something interesting]
  * }
  * </pre>
  * @author Copyright (c) 1997, 1998 by Microstar Software Ltd.
  * @author Written by David Megginson &lt;dmeggins@microstar.com&gt;
  * @version 1.1
  * @deprecated use org.xml.sax.XMLReader
  */
public class XmlParser {

  //
  // Use special cheats that speed up the code (currently about 50%),
  // but may cause problems with future maintenance and add to the
  // class file size (about 500 bytes).
  //
  private final static boolean USE_CHEATS = true;



  //////////////////////////////////////////////////////////////////////
  // Constructors.
  ////////////////////////////////////////////////////////////////////////


  /**
    * Construct a new parser with no associated handler.
    * @see #setHandler
    * @see #parse
    */
  public XmlParser ()
  {
  }


  /**
    * Set the handler that will receive parsing events.
    * @param handler The handler to receive callback events.
    * @see #parse
    * @see XmlHandler
    */
  public void setHandler (XmlHandler handler)
  {
    this.handler = handler;
  }


  /**
    * Parse an XML document from a URI.
    * <p>You may parse a document more than once, but only one thread
    * may call this method for an object at one time.
    * @param systemId The URI of the document.
    * @param publicId The public identifier of the document, or null.
    * @param encoding The suggested encoding, or null if unknown.
    * @exception java.lang.Exception Any exception thrown by your
    *            own handlers, or any derivation of java.io.IOException
    *            thrown by the parser itself.
    */
  public void parse (String systemId, String publicId, String encoding)
    throws java.lang.Exception
  {
    doParse(systemId, publicId, null, null, encoding);
  }


  /**
    * Parse an XML document from a byte stream.
    * <p>The URI that you supply will become the base URI for
    * resolving relative links, but &AElig;lfred will actually read
    * the document from the supplied input stream.
    * <p>You may parse a document more than once, but only one thread
    * may call this method for an object at one time.
    * @param systemId The base URI of the document, or null if not
    *                 known.
    * @param publicId The public identifier of the document, or null
    *                 if not known.
    * @param stream A byte input stream.
    * @param encoding The suggested encoding, or null if unknown.
    * @exception java.lang.Exception Any exception thrown by your
    *            own handlers, or any derivation of java.io.IOException
    *            thrown by the parser itself.
    */
  public void parse (String systemId, String publicId,
		     InputStream stream, String encoding)
    throws java.lang.Exception
  {
    doParse(systemId, publicId, null, stream, encoding);
  }


  /**
    * Parse an XML document from a character stream.
    * <p>The URI that you supply will become the base URI for
    * resolving relative links, but &AElig;lfred will actually read
    * the document from the supplied input stream.
    * <p>You may parse a document more than once, but only one thread
    * may call this method for an object at one time.
    * @param systemId The base URI of the document, or null if not
    *                 known.
    * @param publicId The public identifier of the document, or null
    *                 if not known.
    * @param reader A character stream.
    * @exception java.lang.Exception Any exception thrown by your
    *            own handlers, or any derivation of java.io.IOException
    *            thrown by the parser itself.
    */
  public void parse (String systemId, String publicId, Reader reader)
    throws java.lang.Exception
  {
    doParse(systemId, publicId, reader, null, null);
  }


  private synchronized void doParse (String systemId, String publicId,
				     Reader reader, InputStream stream,
				     String encoding)
    throws java.lang.Exception
  {
    basePublicId = publicId;
    baseURI = systemId;
    baseReader = reader;
    baseInputStream = stream;

    initializeVariables();

				// Set the default entities here.
    setInternalEntity(intern("amp"), "&#38;");
    setInternalEntity(intern("lt"), "&#60;");
    setInternalEntity(intern("gt"), "&#62;");
    setInternalEntity(intern("apos"), "&#39;");
    setInternalEntity(intern("quot"), "&#34;");

    if (handler != null) {
      handler.startDocument();
    }

    pushURL("[document]", basePublicId, baseURI, baseReader, baseInputStream,
	    encoding);

    parseDocument();

    if (handler != null) {
      handler.endDocument();
    }
    cleanupVariables();
  }



  ////////////////////////////////////////////////////////////////////////
  // Constants.
  ////////////////////////////////////////////////////////////////////////

  //
  // Constants for element content type.
  //

  /**
    * Constant: an element has not been declared.
    * @see #getElementContentType
    */
  public final static int CONTENT_UNDECLARED = 0;

  /**
    * Constant: the element has a content model of ANY.
    * @see #getElementContentType
    */
  public final static int CONTENT_ANY = 1;

  /**
    * Constant: the element has declared content of EMPTY.
    * @see #getElementContentType
    */
  public final static int CONTENT_EMPTY = 2;

  /**
    * Constant: the element has mixed content.
    * @see #getElementContentType
    */
  public final static int CONTENT_MIXED = 3;

  /**
    * Constant: the element has element content.
    * @see #getElementContentType
    */
  public final static int CONTENT_ELEMENTS = 4;


  //
  // Constants for the entity type.
  //

  /**
    * Constant: the entity has not been declared.
    * @see #getEntityType
    */
  public final static int ENTITY_UNDECLARED = 0;

  /**
    * Constant: the entity is internal.
    * @see #getEntityType
    */
  public final static int ENTITY_INTERNAL = 1;

  /**
    * Constant: the entity is external, non-XML data.
    * @see #getEntityType
    */
  public final static int ENTITY_NDATA = 2;

  /**
    * Constant: the entity is external XML data.
    * @see #getEntityType
    */
  public final static int ENTITY_TEXT = 3;


  //
  // Constants for attribute type.
  //

  /**
    * Constant: the attribute has not been declared for this element type.
    * @see #getAttributeType
    */
  public final static int ATTRIBUTE_UNDECLARED = 0;

  /**
    * Constant: the attribute value is a string value.
    * @see #getAttributeType
    */
  public final static int ATTRIBUTE_CDATA = 1;

  /**
    * Constant: the attribute value is a unique identifier.
    * @see #getAttributeType
    */
  public final static int ATTRIBUTE_ID = 2;

  /**
    * Constant: the attribute value is a reference to a unique identifier.
    * @see #getAttributeType
    */
  public final static int ATTRIBUTE_IDREF = 3;

  /**
    * Constant: the attribute value is a list of ID references.
    * @see #getAttributeType
    */
  public final static int ATTRIBUTE_IDREFS = 4;

  /**
    * Constant: the attribute value is the name of an entity.
    * @see #getAttributeType
    */
  public final static int ATTRIBUTE_ENTITY = 5;

  /**
    * Constant: the attribute value is a list of entity names.
    * @see #getAttributeType
    */
  public final static int ATTRIBUTE_ENTITIES = 6;

  /**
    * Constant: the attribute value is a name token.
    * @see #getAttributeType
    */
  public final static int ATTRIBUTE_NMTOKEN = 7;

  /**
    * Constant: the attribute value is a list of name tokens.
    * @see #getAttributeType
    */
  public final static int ATTRIBUTE_NMTOKENS = 8;

  /**
    * Constant: the attribute value is a token from an enumeration.
    * @see #getAttributeType
    */
  public final static int ATTRIBUTE_ENUMERATED = 9;

  /**
    * Constant: the attribute is the name of a notation.
    * @see #getAttributeType
    */
  public final static int ATTRIBUTE_NOTATION = 10;


  //
  // When the class is loaded, populate the hash table of
  // attribute types.
  //

  /**
    * Hash table of attribute types.
    */
  private static Hashtable attributeTypeHash;
  static {
    attributeTypeHash = new Hashtable();
    attributeTypeHash.put("CDATA", new Integer(ATTRIBUTE_CDATA));
    attributeTypeHash.put("ID", new Integer(ATTRIBUTE_ID));
    attributeTypeHash.put("IDREF", new Integer(ATTRIBUTE_IDREF));
    attributeTypeHash.put("IDREFS", new Integer(ATTRIBUTE_IDREFS));
    attributeTypeHash.put("ENTITY", new Integer(ATTRIBUTE_ENTITY));
    attributeTypeHash.put("ENTITIES", new Integer(ATTRIBUTE_ENTITIES));
    attributeTypeHash.put("NMTOKEN", new Integer(ATTRIBUTE_NMTOKEN));
    attributeTypeHash.put("NMTOKENS", new Integer(ATTRIBUTE_NMTOKENS));
    attributeTypeHash.put("NOTATION", new Integer(ATTRIBUTE_NOTATION));
  }


  //
  // Constants for supported encodings.
  //
  private final static int ENCODING_UTF_8 = 1;
  private final static int ENCODING_ISO_8859_1 = 2;
  private final static int ENCODING_UCS_2_12 = 3;
  private final static int ENCODING_UCS_2_21 = 4;
  private final static int ENCODING_UCS_4_1234 = 5;
  private final static int ENCODING_UCS_4_4321 = 6;
  private final static int ENCODING_UCS_4_2143 = 7;
  private final static int ENCODING_UCS_4_3412 = 8;


  //
  // Constants for attribute default value.
  //

  /**
    * Constant: the attribute is not declared.
    * @see #getAttributeDefaultValueType
    */
  public final static int ATTRIBUTE_DEFAULT_UNDECLARED = 0;

  /**
    * Constant: the attribute has a literal default value specified.
    * @see #getAttributeDefaultValueType
    * @see #getAttributeDefaultValue
    */
  public final static int ATTRIBUTE_DEFAULT_SPECIFIED = 1;

  /**
    * Constant: the attribute was declared #IMPLIED.
    * @see #getAttributeDefaultValueType
    */
  public final static int ATTRIBUTE_DEFAULT_IMPLIED = 2;

  /**
    * Constant: the attribute was declared #REQUIRED.
    * @see #getAttributeDefaultValueType
    */
  public final static int ATTRIBUTE_DEFAULT_REQUIRED = 3;

  /**
    * Constant: the attribute was declared #FIXED.
    * @see #getAttributeDefaultValueType
    * @see #getAttributeDefaultValue
    */
  public final static int ATTRIBUTE_DEFAULT_FIXED = 4;


  //
  // Constants for input.
  //
  private final static int INPUT_NONE = 0;
  private final static int INPUT_INTERNAL = 1;
  private final static int INPUT_EXTERNAL = 2;
  private final static int INPUT_STREAM = 3;
  private final static int INPUT_BUFFER = 4;
  private final static int INPUT_READER = 5;


  //
  // Flags for reading literals.
  //
  private final static int LIT_CHAR_REF = 1;
  private final static int LIT_ENTITY_REF = 2;
  private final static int LIT_PE_REF = 4;
  private final static int LIT_NORMALIZE = 8;


  //
  // Flags for parsing context.
  //
  private final static int CONTEXT_NONE = 0;
  private final static int CONTEXT_DTD = 1;
  private final static int CONTEXT_ENTITYVALUE = 2;
  private final static int CONTEXT_ATTRIBUTEVALUE = 3;



  //////////////////////////////////////////////////////////////////////
  // Error reporting.
  //////////////////////////////////////////////////////////////////////


  /**
    * Report an error.
    * @param message The error message.
    * @param textFound The text that caused the error (or null).
    * @see XmlHandler#error
    * @see #line
    */
  void error (String message, String textFound, String textExpected)
    throws java.lang.Exception
  {
    errorCount++;
    if (textFound != null) {
      message = message + " (found \"" + textFound + "\")";
    }
    if (textExpected != null) {
      message = message + " (expected \"" + textExpected + "\")";
    }
    if (handler != null) {
      String uri = null;

      if (externalEntity != null) {
	uri = externalEntity.getURL().toString();
      }
      handler.error(message, uri, line, column);
    }
  }


  /**
    * Report a serious error.
    * @param message The error message.
    * @param textFound The text that caused the error (or null).
    */
  void error (String message, char textFound, String textExpected)
    throws java.lang.Exception
  {
    error(message, new Character(textFound).toString(), textExpected);
  }



  //////////////////////////////////////////////////////////////////////
  // Major syntactic productions.
  //////////////////////////////////////////////////////////////////////


  /**
    * Parse an XML document.
    * <pre>
    * [1] document ::= prolog element Misc*
    * </pre>
    * <p>This is the top-level parsing function for a single XML
    * document.  As a minimum, a well-formed document must have
    * a document element, and a valid document must have a prolog
    * as well.
    */
  void parseDocument ()
    throws java.lang.Exception
    {
    char c;

    parseProlog();
    require('<');
    parseElement();
    try
      {
      parseMisc();  //skip all white, PIs, and comments
      c=readCh();   //if this doesn't throw an exception...
      error("unexpected characters after document end",c,null);
      }
    catch (EOFException e)
      {return;}
    }


  /**
    * Skip a comment.
    * <pre>
    * [18] Comment ::= '&lt;!--' ((Char - '-') | ('-' (Char - '-')))* "-->"
    * </pre>
    * <p>(The <code>&lt;!--</code> has already been read.)
    */
  void parseComment ()
    throws java.lang.Exception
  {
    skipUntil("-->");
  }


  /**
    * Parse a processing instruction and do a call-back.
    * <pre>
    * [19] PI ::= '&lt;?' Name (S (Char* - (Char* '?&gt;' Char*)))? '?&gt;'
    * </pre>
    * <p>(The <code>&lt;?</code> has already been read.)
    * <p>An XML processing instruction <em>must</em> begin with
    * a Name, which is the instruction's target.
    */
  void parsePI ()
    throws java.lang.Exception
  {
    String name;

    name = readNmtoken(true);
    if (!tryRead("?>")) {
      requireWhitespace();
      parseUntil("?>");
    }
    if (handler != null) {
      handler.processingInstruction(name, dataBufferToString());
    }
  }


  /**
    * Parse a CDATA marked section.
    * <pre>
    * [20] CDSect ::= CDStart CData CDEnd
    * [21] CDStart ::= '&lt;![CDATA['
    * [22] CData ::= (Char* - (Char* ']]&gt;' Char*))
    * [23] CDEnd ::= ']]&gt;'
    * </pre>
    * <p>(The '&lt;![CDATA[' has already been read.)
    * <p>Note that this just appends characters to the dataBuffer,
    * without actually generating an event.
    */
  void parseCDSect ()
    throws java.lang.Exception
  {
    parseUntil("]]>");
  }


  /**
    * Parse the prolog of an XML document.
    * <pre>
    * [24] prolog ::= XMLDecl? Misc* (Doctypedecl Misc*)?
    * </pre>
    * <p>There are a couple of tricks here.  First, it is necessary to
    * declare the XML default attributes after the DTD (if present)
    * has been read.  Second, it is not possible to expand general
    * references in attribute value literals until after the entire
    * DTD (if present) has been parsed.
    * <p>We do not look for the XML declaration here, because it is
    * handled by pushURL().
    * @see pushURL
    */
  void parseProlog ()
    throws java.lang.Exception
  {
    parseMisc();

    if (tryRead("<!DOCTYPE")) {
      parseDoctypedecl();
      parseMisc();
    }
  }


  /**
    * Parse the XML declaration.
    * <pre>
    * [25] XMLDecl ::= '&lt;?xml' VersionInfo EncodingDecl? SDDecl? S? '?&gt;'
    * [26] VersionInfo ::= S 'version' Eq ('"1.0"' | "'1.0'")
    * [33] SDDecl ::= S 'standalone' Eq "'" ('yes' | 'no') "'"
    *               | S 'standalone' Eq '"' ("yes" | "no") '"'
    * [78] EncodingDecl ::= S 'encoding' Eq QEncoding
    * </pre>
    * <p>([80] to [82] are also significant.)
    * <p>(The <code>&lt;?xml</code> and whitespace have already been read.)
    * <p>TODO: validate value of standalone.
    * @see #parseTextDecl
    * @see #checkEncoding
    */
  void parseXMLDecl (boolean ignoreEncoding)
    throws java.lang.Exception
  {
    String version;
    String encodingName = null;
    String standalone = null;

				// Read the version.
    require("version");
    parseEq();
    version = readLiteral(0);
    if (!version.equals("1.0")) {
      error("unsupported XML version", version, "1.0");
    }

				// Try reading an encoding declaration.
    skipWhitespace();
    if (tryRead("encoding")) {
      parseEq();
      encodingName = readLiteral(0);
      checkEncoding(encodingName, ignoreEncoding);
    }

				// Try reading a standalone declaration
    skipWhitespace();
    if (tryRead("standalone")) {
      parseEq();
      standalone = readLiteral(0);
    }

    skipWhitespace();
    require("?>");
  }


  /**
    * Parse the Encoding PI.
    * <pre>
    * [78] EncodingDecl ::= S 'encoding' Eq QEncoding
    * [79] EncodingPI ::= '&lt;?xml' S 'encoding' Eq QEncoding S? '?&gt;'
    * [80] QEncoding ::= '"' Encoding '"' | "'" Encoding "'"
    * [81] Encoding ::= LatinName
    * [82] LatinName ::= [A-Za-z] ([A-Za-z0-9._] | '-')*
    * </pre>
    * <p>(The <code>&lt;?xml</code>' and whitespace have already been read.)
    * @see #parseXMLDecl
    * @see #checkEncoding
    */
  void parseTextDecl (boolean ignoreEncoding)
    throws java.lang.Exception
  {
    String encodingName = null;
    
				// Read an optional version.
    if (tryRead("version")) {
      String version;
      parseEq();
      version = readLiteral(0);
      if (!version.equals("1.0")) {
	error("unsupported XML version", version, "1.0");
      }
      requireWhitespace();
    }
      

				// Read the encoding.
    require("encoding");
    parseEq();
    encodingName = readLiteral(0);
    checkEncoding(encodingName, ignoreEncoding);

    skipWhitespace();
    require("?>");
  }


  /**
    * Check that the encoding specified makes sense.
    * <p>Compare what the author has specified in the XML declaration
    * or encoding PI with what we have detected.
    * <p>This is also important for distinguishing among the various
    * 7- and 8-bit encodings, such as ISO-LATIN-1 (I cannot autodetect
    * those).
    * @param encodingName The name of the encoding specified by the user.
    * @see #parseXMLDecl
    * @see #parseTextDecl
    */
  void checkEncoding (String encodingName, boolean ignoreEncoding)
    throws java.lang.Exception
  {
    encodingName = encodingName.toUpperCase();

    if (ignoreEncoding) {
      return;
    }

    switch (encoding) {
				// 8-bit encodings
    case ENCODING_UTF_8:
      if (encodingName.equals("ISO-8859-1")) {
	encoding = ENCODING_ISO_8859_1;
      } else if (!encodingName.equals("UTF-8")) {
	error("unsupported 8-bit encoding",
	      encodingName,
	      "UTF-8 or ISO-8859-1");
      }
      break;
				// 16-bit encodings
    case ENCODING_UCS_2_12:
    case ENCODING_UCS_2_21:
      if (!encodingName.equals("ISO-10646-UCS-2") &&
	  !encodingName.equals("UTF-16")) {
	error("unsupported 16-bit encoding",
	      encodingName,
	      "ISO-10646-UCS-2");
      }
      break;
				// 32-bit encodings
    case ENCODING_UCS_4_1234:
    case ENCODING_UCS_4_4321:
    case ENCODING_UCS_4_2143:
    case ENCODING_UCS_4_3412:
      if (!encodingName.equals("ISO-10646-UCS-4")) {
	error("unsupported 32-bit encoding",
	      encodingName,
	      "ISO-10646-UCS-4");
      }
    }
  }


  /**
    * Parse miscellaneous markup outside the document element and DOCTYPE
    * declaration.
    * <pre>
    * [27] Misc ::= Comment | PI | S
    * </pre>
    */
  void parseMisc ()
    throws java.lang.Exception
    {
    while (true)
      {
      skipWhitespace();
      if (tryRead("<?"))
        {parsePI();}
      else if (tryRead("<!--"))
        {parseComment();}
      else
        {return;}
      }
    }


  /**
    * Parse a document type declaration.
    * <pre>
    * [28] doctypedecl ::= '&lt;!DOCTYPE' S Name (S ExternalID)? S?
    *                      ('[' %markupdecl* ']' S?)? '&gt;'
    * </pre>
    * <p>(The <code>&lt;!DOCTYPE</code> has already been read.)
    */
  void parseDoctypedecl ()
    throws java.lang.Exception
  {
    char c;
    String doctypeName, ids[];

				// Read the document type name.
    requireWhitespace();
    doctypeName = readNmtoken(true);

				// Read the ExternalIDs.
    skipWhitespace();
    ids = readExternalIds(false);

				// Look for a declaration subset.
    skipWhitespace();
    if (tryRead('[')) {

				// loop until the subset ends
      while (true) {
	context = CONTEXT_DTD;
	skipWhitespace();
	context = CONTEXT_NONE;
	if (tryRead(']')) {
	  break;		// end of subset
	} else {
	  context = CONTEXT_DTD;
	  parseMarkupdecl();
	  context = CONTEXT_NONE;
	}
      }
    }

				// Read the external subset, if any
    if (ids[1] != null) {
      pushURL("[external subset]", ids[0], ids[1], null, null, null);

				// Loop until we end up back at '>'
      while (true) {
	context = CONTEXT_DTD;
	skipWhitespace();
	context = CONTEXT_NONE;
	if (tryRead('>')) {
	  break;
	} else {
	  context = CONTEXT_DTD;
	  parseMarkupdecl();
	  context = CONTEXT_NONE;
	}
      }
    } else {
				// No external subset.
      skipWhitespace();
      require('>');
    }

    if (handler != null) {
      handler.doctypeDecl(doctypeName, ids[0], ids[1]);
    }

				// Expand general entities in
				// default values of attributes.
				// (Do this after the doctypeDecl
				// event!).
    // expandAttributeDefaultValues();
  }


  /**
    * Parse a markup declaration in the internal or external DTD subset.
    * <pre>
    * [29] markupdecl ::= ( %elementdecl | %AttlistDecl | %EntityDecl |
    *                       %NotationDecl | %PI | %S | %Comment |
    *                       InternalPERef )
    * [30] InternalPERef ::= PEReference
    * [31] extSubset ::= (%markupdecl | %conditionalSect)*
    * </pre>
    */
  void parseMarkupdecl ()
    throws java.lang.Exception
  {
    if (tryRead("<!ELEMENT")) {
      parseElementdecl();
    } else if (tryRead("<!ATTLIST")) {
      parseAttlistDecl();
    } else if (tryRead("<!ENTITY")) {
      parseEntityDecl();
    } else if (tryRead("<!NOTATION")) {
      parseNotationDecl();
    } else if (tryRead("<?")) {
      parsePI();
    } else if (tryRead("<!--")) {
      parseComment();
    } else if (tryRead("<![")) {
      parseConditionalSect();
    } else {
      error("expected markup declaration", null, null);
    }
  }


  /**
    * Parse an element, with its tags.
    * <pre>
    * [33] STag ::= '&lt;' Name (S Attribute)* S? '&gt;' [WFC: unique Att spec]
    * [38] element ::= EmptyElement | STag content ETag
    * [39] EmptyElement ::= '&lt;' Name (S Attribute)* S? '/&gt;'
    *                       [WFC: unique Att spec]
    * </pre>
    * <p>(The '&lt;' has already been read.)
    * <p>NOTE: this method actually chains onto parseContent(), if necessary,
    * and parseContent() will take care of calling parseETag().
    */
  void parseElement ()
    throws java.lang.Exception
  {
    String gi;
    char c;
    int oldElementContent = currentElementContent;
    String oldElement = currentElement;

				// This is the (global) counter for the
				// array of specified attributes.
    tagAttributePos = 0;

				// Read the element type name.
    gi = readNmtoken(true);

				// Determine the current content type.
    currentElement = gi;
    currentElementContent = getElementContentType(gi);
    if (currentElementContent == CONTENT_UNDECLARED) {
      currentElementContent = CONTENT_ANY;
    }

				// Read the attributes, if any.
				// After this loop, we should be just
				// in front of the closing delimiter.
    skipWhitespace();
    c = readCh();
    while (c != '/' && c != '>') {
      unread(c);
      parseAttribute(gi);
      skipWhitespace();
      c = readCh();
    }
    unread(c);

				// Supply any defaulted attributes.
    Enumeration atts = declaredAttributes(gi);
    if (atts != null) {
      String aname;
    loop: while (atts.hasMoreElements()) {
      aname = (String)atts.nextElement();
				// See if it was specified.
      for (int i = 0; i < tagAttributePos; i++) {
	if (tagAttributes[i] == aname) {
	  continue loop;
	}
      }
				// I guess not...
      if (handler != null) {
	handler.attribute(aname,
			  getAttributeExpandedValue(gi, aname),
			  false);
      }
    }
    }

				// Figure out if this is a start tag
				// or an empty element, and dispatch an
				// event accordingly.
    c = readCh();
    switch (c) {
    case '>':
      if (handler != null) {
	handler.startElement(gi);
      }
      parseContent();
      break;
    case '/':
      require('>');
      if (handler != null) {
	handler.startElement(gi);
	handler.endElement(gi);
      }
      break;
    }

				// Restore the previous state.
    currentElement = oldElement;
    currentElementContent = oldElementContent;
  }


  /**
    * Parse an attribute assignment.
    * <pre>
    * [34] Attribute ::= Name Eq AttValue
    * </pre>
    * @param name The name of the attribute's element.
    * @see XmlHandler#attribute
    */
  void parseAttribute (String name)
    throws java.lang.Exception
  {
    String aname;
    int type;
    String value;

				// Read the attribute name.
    aname = readNmtoken(true).intern();
    type = getAttributeDefaultValueType(name, aname);

				// Parse '='
    parseEq();

				// Read the value, normalizing whitespace
				// if it is not CDATA.
    if (type == ATTRIBUTE_CDATA || type == ATTRIBUTE_UNDECLARED) {
      value = readLiteral(LIT_CHAR_REF | LIT_ENTITY_REF);
    } else {
      value = readLiteral(LIT_CHAR_REF | LIT_ENTITY_REF | LIT_NORMALIZE);
    }

				// Inform the handler about the
				// attribute.
    if (handler != null) {
      handler.attribute(aname, value, true);
    }
    dataBufferPos = 0;

				// Note that the attribute has been
				// specified.
    if (tagAttributePos == tagAttributes.length) {
      String newAttrib[] = new String[tagAttributes.length * 2];
      System.arraycopy(tagAttributes, 0, newAttrib, 0, tagAttributePos);
      tagAttributes = newAttrib;
    }
    tagAttributes[tagAttributePos++] = aname;
  }


  /**
    * Parse an equals sign surrounded by optional whitespace.
    * [35] Eq ::= S? '=' S?
    */
  void parseEq ()
    throws java.lang.Exception
  {
    skipWhitespace();
    require('=');
    skipWhitespace();
  }


  /**
    * Parse an end tag.
    * [36] ETag ::= '</' Name S? '>'
    * *NOTE: parseContent() chains to here.
    */
  void parseETag ()
    throws java.lang.Exception
  {
    String name;
    name = readNmtoken(true);
    if (name != currentElement) {
      error("mismatched end tag", name, currentElement);
    }
    skipWhitespace();
    require('>');
    if (handler != null) {
      handler.endElement(name);
    }
  }


  /**
    * Parse the content of an element.
    * [37] content ::= (element | PCData | Reference | CDSect | PI | Comment)*
    * [68] Reference ::= EntityRef | CharRef
    */
  void parseContent ()
    throws java.lang.Exception
  {
    String data;
    char c;

    while (true) {

      switch (currentElementContent) {
      case CONTENT_ANY:
      case CONTENT_MIXED:
	parsePCData();
	break;
      case CONTENT_ELEMENTS:
	parseWhitespace();
	break;
      }

				// Handle delimiters
      c = readCh();
      switch (c) {

      case '&':			// Found "&"
	c = readCh();
	if (c == '#') {
	  parseCharRef();
	} else {
	  unread(c);
	  parseEntityRef(true);
	}
	break;

      case '<':			// Found "<"

	c = readCh();
	switch (c) {

	case '!':		// Found "<!"
	  c = readCh();
	  switch (c) {
	  case '-':		// Found "<!-"
	    require('-');
	    parseComment();
	    break;
	  case '[':		// Found "<!["
	    require("CDATA[");
	    parseCDSect();
	    break;
	  default:
	    error("expected comment or CDATA section", c, null);
	    break;
	  }
	  break;

	case '?':		// Found "<?"
	  dataBufferFlush();
	  parsePI();
	  break;

	case '/':		// Found "</"
	  dataBufferFlush();
	  parseETag();
	  return;

	default:		// Found "<" followed by something else
	  dataBufferFlush();
	  unread(c);
	  parseElement();
	  break;
	}
      }
    }
  }


  /**
    * Parse an element type declaration.
    * [40] elementdecl ::= '<!ELEMENT' S %Name S (%S S)? %contentspec S? '>'
    *                      [VC: Unique Element Declaration]
    * *NOTE: the '<!ELEMENT' has already been read.
    */
  void parseElementdecl ()
    throws java.lang.Exception
  {
    String name;

    requireWhitespace();
				// Read the element type name.
    name = readNmtoken(true);

    requireWhitespace();
				// Read the content model.
    parseContentspec(name);

    skipWhitespace();
    require('>');
  }


  /**
    * Content specification.
    * [41] contentspec ::= 'EMPTY' | 'ANY' | Mixed | elements
    */
  void parseContentspec (String name)
    throws java.lang.Exception
  {
    if (tryRead("EMPTY")) {
      setElement(name, CONTENT_EMPTY, null, null);
      return;
    } else if (tryRead("ANY")) {
      setElement(name, CONTENT_ANY, null, null);
      return;
    } else {
      require('(');
      dataBufferAppend('(');
      skipWhitespace();
      if (tryRead("#PCDATA")) {
	dataBufferAppend("#PCDATA");
	parseMixed();
	setElement(name, CONTENT_MIXED, dataBufferToString(), null);
      } else {
	parseElements();
	setElement(name, CONTENT_ELEMENTS, dataBufferToString(), null);
      }
    }
  }


  /**
    * Parse an element-content model.
    * [42] elements ::= (choice | seq) ('?' | '*' | '+')?
    * [44] cps ::= S? %cp S?
    * [45] choice ::= '(' S? %ctokplus (S? '|' S? %ctoks)* S? ')'
    * [46] ctokplus ::= cps ('|' cps)+
    * [47] ctoks ::= cps ('|' cps)*
    * [48] seq ::= '(' S? %stoks (S? ',' S? %stoks)* S? ')'
    * [49] stoks ::= cps (',' cps)*
    * *NOTE: the opening '(' and S have already been read.
    * *TODO: go over parameter entity boundaries more carefully.
    */
  void parseElements ()
    throws java.lang.Exception
  {
    char c;
    char sep;

				// Parse the first content particle
    skipWhitespace();
    parseCp();

				// Check for end or for a separator.
    skipWhitespace();
    c = readCh();
    switch (c) {
    case ')':
      dataBufferAppend(')');
      c = readCh();
      switch (c) {
      case '*':
      case '+':
      case '?':
	dataBufferAppend(c);
	break;
      default:
	unread(c);
      }
      return;
    case ',':			// Register the separator.
    case '|':
      sep = c;
      dataBufferAppend(c);
      break;
    default:
      error("bad separator in content model", c, null);
      return;
    }

				// Parse the rest of the content model.
    while (true) {
      skipWhitespace();
      parseCp();
      skipWhitespace();
      c = readCh();
      if (c == ')') {
	dataBufferAppend(')');
	break;
      } else if (c != sep) {
	error("bad separator in content model", c, null);
	return;
      } else {
	dataBufferAppend(c);
      }
    }

				// Check for the occurrence indicator.
    c = readCh();
    switch (c) {
    case '?':
    case '*':
    case '+':
      dataBufferAppend(c);
      return;
    default:
      unread(c);
      return;
    }
  }


  /**
    * Parse a content particle.
    * [43] cp ::= (Name | choice | seq) ('?' | '*' | '+')
    * *NOTE: I actually use a slightly different production here:
    *        cp ::= (elements | (Name ('?' | '*' | '+')?))
    */
  void parseCp ()
    throws java.lang.Exception
  {
    char c;

    if (tryRead('(')) {
      dataBufferAppend('(');
      parseElements();
    } else {
      dataBufferAppend(readNmtoken(true));
      c = readCh();
      switch (c) {
      case '?':
      case '*':
      case '+':
	dataBufferAppend(c);
	break;
      default:
	unread(c);
	break;
      }
    }
  }


  /**
    * Parse mixed content.
    * [50] Mixed ::= '(' S? %( %'#PCDATA' (S? '|' S? %Mtoks)* ) S? ')*'
    *              | '(' S? %('#PCDATA') S? ')'
    * [51] Mtoks ::= %Name (S? '|' S? %Name)*
    * *NOTE: the S and '#PCDATA' have already been read.
    */
  void parseMixed ()
    throws java.lang.Exception
  {
    char c;

				// Check for PCDATA alone.
    skipWhitespace();
    if (tryRead(')')) {
      dataBufferAppend(")*");
      tryRead('*');
      return;
    }

				// Parse mixed content.
    skipWhitespace();
    while (!tryRead(")*")) {
      require('|');
      dataBufferAppend('|');
      skipWhitespace();
      dataBufferAppend(readNmtoken(true));
      skipWhitespace();
    }
    dataBufferAppend(")*");
  }


  /**
    * Parse an attribute list declaration.
    * [52] AttlistDecl ::= '<!ATTLIST' S %Name S? %AttDef+ S? '>'
    * *NOTE: the '<!ATTLIST' has already been read.
    */
  void parseAttlistDecl ()
    throws java.lang.Exception
  {
    String elementName;

    requireWhitespace();
    elementName = readNmtoken(true);
    requireWhitespace();
    while (!tryRead('>')) {
      parseAttDef(elementName);
      skipWhitespace();
    }
  }


  /**
    * Parse a single attribute definition.
    * [53] AttDef ::= S %Name S %AttType S %Default
    */
  void parseAttDef (String elementName)
    throws java.lang.Exception
  {
    String name;
    int type;
    String enumeration = null;

				// Read the attribute name.
    name = readNmtoken(true);

				// Read the attribute type.
    requireWhitespace();
    type = readAttType();

				// Get the string of enumerated values
				// if necessary.
    if (type == ATTRIBUTE_ENUMERATED || type == ATTRIBUTE_NOTATION) {
      enumeration = dataBufferToString();
    }

				// Read the default value.
    requireWhitespace();
    parseDefault(elementName, name, type, enumeration);
  }


  /**
    * Parse the attribute type.
    * [54] AttType ::= StringType | TokenizedType | EnumeratedType
    * [55] StringType ::= 'CDATA'
    * [56] TokenizedType ::= 'ID' | 'IDREF' | 'IDREFS' | 'ENTITY' | 'ENTITIES' |
    *                        'NMTOKEN' | 'NMTOKENS'
    * [57] EnumeratedType ::= NotationType | Enumeration
    * *TODO: validate the type!!
    */
  int readAttType ()
    throws java.lang.Exception
  {
    String typeString;
    Integer type;

    if (tryRead('(')) {
      parseEnumeration();
      return ATTRIBUTE_ENUMERATED;
    } else {
      typeString = readNmtoken(true);
      if (typeString.equals("NOTATION")) {
	parseNotationType();
      }
      type = (Integer)attributeTypeHash.get(typeString);
      if (type == null) {
	error("illegal attribute type", typeString, null);
	return ATTRIBUTE_UNDECLARED;
      } else {
	return type.intValue();
      }
    }
  }


  /**
    * Parse an enumeration.
    * [60] Enumeration ::= '(' S? %Etoks (S? '|' S? %Etoks)* S? ')'
    * [61] Etoks ::= %Nmtoken (S? '|' S? %Nmtoken)*
    * *NOTE: the '(' has already been read.
    */
  void parseEnumeration ()
    throws java.lang.Exception
  {
    char c;

    dataBufferAppend('(');

				// Read the first token.
    skipWhitespace();
    dataBufferAppend(readNmtoken(true));
				// Read the remaining tokens.
    skipWhitespace();
    while (!tryRead(')')) {
      require('|');
      dataBufferAppend('|');
      skipWhitespace();
      dataBufferAppend(readNmtoken(true));
      skipWhitespace();
    }
    dataBufferAppend(')');
  }


  /**
    * Parse a notation type for an attribute.
    * [58] NotationType ::= %'NOTATION' S '(' S? %Ntoks (S? '|' S? %Ntoks)*
    *                       S? ')'
    * [59] Ntoks ::= %Name (S? '|' S? %Name)
    * *NOTE: the 'NOTATION' has already been read
    */
  void parseNotationType ()
    throws java.lang.Exception
  {
    requireWhitespace();
    require('(');

    parseEnumeration();
  }


  /**
    * Parse the default value for an attribute.
    * [62] Default ::= '#REQUIRED' | '#IMPLIED' | ((%'#FIXED' S)? %AttValue
    */
  void parseDefault (String elementName, String name, int type, String enumeration)
    throws java.lang.Exception
  {
    int valueType = ATTRIBUTE_DEFAULT_SPECIFIED;
    String value = null;
    boolean normalizeWSFlag;

    if (tryRead('#')) {
      if (tryRead("FIXED")) {
	valueType = ATTRIBUTE_DEFAULT_FIXED;
	requireWhitespace();
	context = CONTEXT_ATTRIBUTEVALUE;
	value = readLiteral(LIT_CHAR_REF);
	context = CONTEXT_DTD;
      } else if (tryRead("REQUIRED")) {
	valueType = ATTRIBUTE_DEFAULT_REQUIRED;
      } else if (tryRead("IMPLIED")) {
	valueType = ATTRIBUTE_DEFAULT_IMPLIED;
      } else {
	error("illegal keyword for attribute default value", null, null);
      }
    } else {
      context = CONTEXT_ATTRIBUTEVALUE;
      value = readLiteral(LIT_CHAR_REF);
      context = CONTEXT_DTD;
    }
    setAttribute(elementName, name, type, enumeration, value, valueType);
  }


  /**
    * Parse a conditional section.
    * [63] conditionalSect ::= includeSect || ignoreSect
    * [64] includeSect ::= '<![' %'INCLUDE' '[' (%markupdecl*)* ']]>'
    * [65] ignoreSect ::= '<![' %'IGNORE' '[' ignoreSectContents* ']]>'
    * [66] ignoreSectContents ::= ((SkipLit | Comment | PI) -(Char* ']]>'))
    *                           | ('<![' ignoreSectContents* ']]>')
    *                           | (Char - (']' | [<'"]))
    *                           | ('<!' (Char - ('-' | '[')))
    * *NOTE: the '<![' has already been read.
    * *TODO: verify that I am handling ignoreSectContents right.
    */
  void parseConditionalSect ()
    throws java.lang.Exception
  {
    skipWhitespace();
    if (tryRead("INCLUDE")) {
      skipWhitespace();
      require('[');
      skipWhitespace();
      while (!tryRead("]]>")) {
	parseMarkupdecl();
	skipWhitespace();
      }
    } else if (tryRead("IGNORE")) {
      skipWhitespace();
      require('[');
      int nesting = 1;
      char c;
      for (int nest = 1; nest > 0; ) {
	c = readCh();
	switch (c) {
	case '<':
	  if (tryRead("![")) {
	    nest++;
	  }
	case ']':
	  if (tryRead("]>")) {
	    nest--;
	  }
	}
      }
    } else {
      error("conditional section must begin with INCLUDE or IGNORE",
	    null, null);
    }
  }


  /**
    * Read a character reference.
    * [67] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';'
    * *NOTE: the '&#' has already been read.
    */
  void parseCharRef ()
    throws java.lang.Exception
  {
    int value = 0;
    char c;

    if (tryRead('x')) {
      loop1: while (true) {
	c = readCh();
	switch (c) {
	case '0':
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':
	case 'a':
	case 'A':
	case 'b':
	case 'B':
	case 'c':
	case 'C':
	case 'd':
	case 'D':
	case 'e':
	case 'E':
	case 'f':
	case 'F':
	  value *= 16;
	  value += Integer.parseInt(new Character(c).toString(), 16);
	  break;
	case ';':
	  break loop1;
	default:
	  error("illegal character in character reference", c, null);
	  break loop1;
	}
      }
    } else {
      loop2: while (true) {
	c = readCh();
	switch (c) {
	case '0':
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':
	  value *= 10;
	  value += Integer.parseInt(new Character(c).toString(), 10);
	  break;
	case ';':
	  break loop2;
	default:
	  error("illegal character in character reference", c, null);
	  break loop2;
	}
      }
    }

    // Check for surrogates: 00000000 0000xxxx yyyyyyyy zzzzzzzz
    //  (1101|10xx|xxyy|yyyy + 1101|11yy|zzzz|zzzz: 
    if (value <= 0x0000ffff) {
				// no surrogates needed
      dataBufferAppend((char)value);
    } else if (value <= 0x000fffff) {
				// > 16 bits, surrogate needed
      dataBufferAppend((char)(0xd8 | ((value & 0x000ffc00) >> 10)));
      dataBufferAppend((char)(0xdc | (value & 0x0003ff)));
    } else {
				// too big for surrogate
      error("character reference " + value + " is too large for UTF-16",
	    new Integer(value).toString(), null);
    }
  }


  /**
    * Parse a reference.
    * [69] EntityRef ::= '&' Name ';'
    * *NOTE: the '&' has already been read.
    * @param externalAllowed External entities are allowed here.
    */
  void parseEntityRef (boolean externalAllowed)
    throws java.lang.Exception
  {
    String name;

    name = readNmtoken(true);
    require(';');
    switch (getEntityType(name)) {
    case ENTITY_UNDECLARED:
      error("reference to undeclared entity", name, null);
      break;
    case ENTITY_INTERNAL:
      pushString(name, getEntityValue(name));
      break;
    case ENTITY_TEXT:
      if (externalAllowed) {
	pushURL(name, getEntityPublicId(name),
		getEntitySystemId(name),
		null, null, null);
      } else {
	error("reference to external entity in attribute value.", name, null);
      }
      break;
    case ENTITY_NDATA:
      if (externalAllowed) {
	error("data entity reference in content", name, null);
      } else {
	error("reference to external entity in attribute value.", name, null);
      }
      break;
    }
  }


  /**
    * Parse a parameter entity reference.
    * [70] PEReference ::= '%' Name ';'
    * *NOTE: the '%' has already been read.
    */
  void parsePEReference (boolean isEntityValue)
    throws java.lang.Exception
  {
    String name;

    name = "%" + readNmtoken(true);
    require(';');
    switch (getEntityType(name)) {
    case ENTITY_UNDECLARED:
      error("reference to undeclared parameter entity", name, null);
      break;
    case ENTITY_INTERNAL:
      if (isEntityValue) {
	pushString(name, getEntityValue(name));
      } else {
	pushString(name, " " + getEntityValue(name) + ' ');
      }
      break;
    case ENTITY_TEXT:
      if (isEntityValue) {
	pushString(null, " ");
      }
      pushURL(name, getEntityPublicId(name),
	      getEntitySystemId(name),
	      null, null, null);
      if (isEntityValue) {
	pushString(null, " ");
      }
      break;
    }
  }


  /**
    * Parse an entity declaration.
    * [71] EntityDecl ::= '<!ENTITY' S %Name S %EntityDef S? '>'
    *                   | '<!ENTITY' S '%' S %Name S %EntityDef S? '>'
    * [72] EntityDef ::= EntityValue | ExternalDef
    * [73] ExternalDef ::= ExternalID %NDataDecl?
    * [74] ExternalID ::= 'SYSTEM' S SystemLiteral
    *                   | 'PUBLIC' S PubidLiteral S SystemLiteral
    * [75] NDataDecl ::= S %'NDATA' S %Name
    * *NOTE: the '<!ENTITY' has already been read.
    */
  void parseEntityDecl ()
    throws java.lang.Exception
  {
    char c;
    boolean peFlag = false;
    String name, value, notationName, ids[];

				// Check for a parameter entity.
    requireWhitespace();
    if (tryRead('%')) {
      peFlag = true;
      requireWhitespace();
    }

				// Read the entity name, and prepend
				// '%' if necessary.
    name = readNmtoken(true);
    if (peFlag) {
      name = "%" + name;
    }

				// Read the entity value.
    requireWhitespace();
    c = readCh();
    unread(c);
    if (c == '"' || c == '\'') {
				// Internal entity.
      context = CONTEXT_ENTITYVALUE;
      value = readLiteral(LIT_CHAR_REF|LIT_PE_REF);
      context = CONTEXT_DTD;
      setInternalEntity(name,value);
    } else {
				// Read the external IDs
      ids = readExternalIds(false);
      if (ids[1] == null) {
	error("system identifer missing", name, null);
      }

				// Check for NDATA declaration.
      skipWhitespace();
      if (tryRead("NDATA")) {
	requireWhitespace();
	notationName = readNmtoken(true);
	setExternalDataEntity(name, ids[0], ids[1], notationName);
      } else {
	setExternalTextEntity(name, ids[0], ids[1]);
      }
    }

				// Finish the declaration.
    skipWhitespace();
    require('>');
  }


  /**
    * Parse a notation declaration.
    * [81] NotationDecl ::= '<!NOTATION' S %Name S %ExternalID S? '>'
    * *NOTE: the '<!NOTATION' has already been read.
    */
  void parseNotationDecl ()
    throws java.lang.Exception
  {
    String nname, ids[];
    

    requireWhitespace();
    nname = readNmtoken(true);

    requireWhitespace();

				// Read the external identifiers.
    ids = readExternalIds(true);
    if (ids[0] == null && ids[1] == null) {
      error("external identifer missing", nname, null);
    }

				// Register the notation.
    setNotation(nname, ids[0], ids[1]);

    skipWhitespace();
    require('>');
  }


  /**
    * Parse PCDATA.
    * <pre>
    * [16] PCData ::= [^&lt;&amp;]*
    * </pre>
    * <p>The trick here is that the data stays in the dataBuffer without
    * necessarily being converted to a string right away.
    */
  void parsePCData ()
    throws java.lang.Exception
  {
    char c;

				// Start with a little cheat -- in most
				// cases, the entire sequence of
				// character data will already be in
				// the readBuffer; if not, fall through to
				// the normal approach.
    if (USE_CHEATS) {
      int lineAugment = 0;
      int columnAugment = 0;

      loop: for (int i = readBufferPos; i < readBufferLength; i++) {
	switch (readBuffer[i]) {
	case '\n':
	  lineAugment++;
	  columnAugment = 0;
	  break;
	case '&':
	case '<':
	  int start = readBufferPos;
	  columnAugment++;
	  readBufferPos = i;
	  if (lineAugment > 0) {
	    line += lineAugment;
	    column = columnAugment;
	  } else {
	    column += columnAugment;
	  }
	  dataBufferAppend(readBuffer, start, i-start);
	  return;
	default:
	  columnAugment++;
	}
      }
    }

				// OK, the cheat didn't work; start over
				// and do it by the book.
    while (true) {
      c = readCh();
      switch (c) {
      case '<':
      case '&':
	unread(c);
	return;
      default:
	dataBufferAppend(c);
	break;
      }
    }
  }



  //////////////////////////////////////////////////////////////////////
  // High-level reading and scanning methods.
  //////////////////////////////////////////////////////////////////////

  /**
    * Require whitespace characters.
    * [1] S ::= (#x20 | #x9 | #xd | #xa)+
    */
  void requireWhitespace ()
    throws java.lang.Exception
  {
    char c = readCh();
    if (isWhitespace(c)) {
      skipWhitespace();
    } else {
      error("whitespace expected", c, null);
    }
  }


  /**
    * Parse whitespace characters, and leave them in the data buffer.
    */
  void parseWhitespace ()
    throws java.lang.Exception
  {
    char c = readCh();
    while (isWhitespace(c)) {
      dataBufferAppend(c);
      c = readCh();
    }
    unread(c);
  }


  /**
    * Skip whitespace characters.
    * [1] S ::= (#x20 | #x9 | #xd | #xa)+
    */
  void skipWhitespace ()
    throws java.lang.Exception
  {
				// Start with a little cheat.  Most of
				// the time, the white space will fall
				// within the current read buffer; if
				// not, then fall through.
    if (USE_CHEATS) {
      int lineAugment = 0;
      int columnAugment = 0;

      loop: for (int i = readBufferPos; i < readBufferLength; i++) {
	switch (readBuffer[i]) {
	case ' ':
	case '\t':
	case '\r':
	  columnAugment++;
	  break;
	case '\n':
	  lineAugment++;
	  columnAugment = 0;
	  break;
	case '%':
	  if (context == CONTEXT_DTD || context == CONTEXT_ENTITYVALUE) {
	    break loop;
	  } // else fall through...
	default:
	  readBufferPos = i;
	  if (lineAugment > 0) {
	    line += lineAugment;
	    column = columnAugment;
	  } else {
	    column += columnAugment;
	  }
	  return;
	}
      }
    }

				// OK, do it by the book.
    char c = readCh();
    while (isWhitespace(c)) {
      c = readCh();
    }
    unread(c);
  }


  /**
    * Read a name or name token.
    * [5] Name ::= (Letter | '_' | ':') (NameChar)*
    * [7] Nmtoken ::= (NameChar)+
    * *NOTE: [6] is implemented implicitly where required.
    */
  String readNmtoken (boolean isName)
    throws java.lang.Exception
  {
    char c;

    if (USE_CHEATS) {
      loop: for (int i = readBufferPos; i < readBufferLength; i++) {
	switch (readBuffer[i]) {
	case '%':
	  if (context == CONTEXT_DTD || context == CONTEXT_ENTITYVALUE) {
	    break loop;
	  } // else fall through...
	case '<':
	case '>':
	case '&':
	case ',':
	case '|':
	case '*':
	case '+':
	case '?':
	case ')':
	case '=':
	case '\'':
	case '"':
	case '[':
	case ' ':
	case '\t':
	case '\r':
	case '\n':
	case ';':
	case '/':
	case '#':
	  int start = readBufferPos;
	  if (i == start) {
	    error("name expected", readBuffer[i], null);
	  }
	  readBufferPos = i;
	  return intern(readBuffer, start, i - start);
	}
      }
    }

    nameBufferPos = 0;

				// Read the first character.
    loop: while (true) {
      c = readCh();
      switch (c) {
      case '%':
      case '<':
      case '>':
      case '&':
      case ',':
      case '|':
      case '*':
      case '+':
      case '?':
      case ')':
      case '=':
      case '\'':
      case '"':
      case '[':
      case ' ':
      case '\t':
      case '\n':
      case '\r':
      case ';':
      case '/':
	unread(c);
	if (nameBufferPos == 0) {
	  error("name expected", null, null);
	}
	String s = intern(nameBuffer,0,nameBufferPos);
	nameBufferPos = 0;
	return s;
      default:
	nameBuffer =
	  (char[])extendArray(nameBuffer, nameBuffer.length, nameBufferPos);
	nameBuffer[nameBufferPos++] = c;
      }
    }
  }


  /**
    * Read a literal.
    * [10] AttValue ::= '"' ([^<&"] | Reference)* '"'
    *                 | "'" ([^<&'] | Reference)* "'"
    * [11] SystemLiteral ::= '"' URLchar* '"' | "'" (URLchar - "'")* "'"
    * [13] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
    * [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"'
    *                   | "'" ([^%&'] | PEReference | Reference)* "'"
    */
  String readLiteral (int flags)
    throws java.lang.Exception
  {
    char delim, c;
    int startLine = line;

				// Find the delimiter.
    delim = readCh();
    if (delim != '"' && delim != '\'' && delim != (char)0) {
      error("expected '\"' or \"'\"", delim, null);
      return null;
    }

				// Read the literal.
    try {
      c = readCh();

    loop: while (c != delim) {
      switch (c) {
				// Literals never have line ends
      case '\n':
      case '\r':
	c = ' ';
	break;
				// References may be allowed
      case '&':
	if ((flags & LIT_CHAR_REF) > 0) {
	  c = readCh();
	  if (c == '#') {
	    parseCharRef();
	    c = readCh();
	    continue loop;		// check the next character
	  } else if ((flags & LIT_ENTITY_REF) > 0) {
	    unread(c);
	    parseEntityRef(false);
	    c = readCh();
	    continue loop;
	  } else {
	    dataBufferAppend('&');
	  }
	}
	break;

      default:
	break;
      }
      dataBufferAppend(c);
      c = readCh();
    }
    } catch (EOFException e) {
      error("end of input while looking for delimiter (started on line "
	    + startLine + ')', null, new Character(delim).toString());
    }

				// Normalise whitespace if necessary.
    if ((flags & LIT_NORMALIZE) > 0) {
      dataBufferNormalize();
    }

				// Return the value.
    return dataBufferToString();
  }


  /**
    * Try reading external identifiers.
    * <p>The system identifier is not required for notations.
    * @param inNotation Are we in a notation?
    * @return A two-member String array containing the identifiers.
    */
  String[] readExternalIds (boolean inNotation)
    throws java.lang.Exception
  {
    char c;
    String ids[] = new String[2];

    if (tryRead("PUBLIC")) {
      requireWhitespace();
      ids[0] = readLiteral(LIT_NORMALIZE); // public id
      if (inNotation) {
	skipWhitespace();
	if (tryRead('"') || tryRead('\'')) {
	  ids[1] = readLiteral(0);
	}
      } else {
	requireWhitespace();
	ids[1] = readLiteral(0); // system id
      }
    } else if (tryRead("SYSTEM")) {
      requireWhitespace();
      ids[1] = readLiteral(0);	// system id
    }

    return ids;
  }


  /**
    * Test if a character is whitespace.
    * <pre>
    * [1] S ::= (#x20 | #x9 | #xd | #xa)+
    * </pre>
    * @param c The character to test.
    * @return true if the character is whitespace.
    */
  final boolean isWhitespace (char c)
  {
    switch ((int)c) {
    case 0x20:
    case 0x09:
    case 0x0d:
    case 0x0a:
      return true;
    default:
      return false;
    }
  }



  //////////////////////////////////////////////////////////////////////
  // Utility routines.
  //////////////////////////////////////////////////////////////////////


  /**
    * Add a character to the data buffer.
    */
  void dataBufferAppend (char c)
  {
				// Expand buffer if necessary.
    dataBuffer =
      (char[])extendArray(dataBuffer, dataBuffer.length, dataBufferPos);
    dataBuffer[dataBufferPos++] = c;
  }


  /** 
    * Add a string to the data buffer.
    */
  void dataBufferAppend (String s)
  {
    dataBufferAppend(s.toCharArray(), 0, s.length());
  }


  /**
    * Append (part of) a character array to the data buffer.
    */
  void dataBufferAppend (char ch[], int start, int length)
  {
    dataBuffer =
      (char[])extendArray(dataBuffer, dataBuffer.length,
			  dataBufferPos + length);
    System.arraycopy((Object)ch, start,
		     (Object)dataBuffer, dataBufferPos,
		     length);
    dataBufferPos += length;
  }


  /**
    * Normalise whitespace in the data buffer.
    */
  void dataBufferNormalize ()
  {
    int i = 0;
    int j = 0;
    int end = dataBufferPos;

				// Skip whitespace at the start.
    while (j < end && isWhitespace(dataBuffer[j])) {
      j++;
    }

				// Skip whitespace at the end.
    while (end > j && isWhitespace(dataBuffer[end - 1])) {
      end --;
    }

				// Start copying to the left.
    while (j < end) {

      char c = dataBuffer[j++];

				// Normalise all other whitespace to
				// a single space.
      if (isWhitespace(c)) {
	while (j < end && isWhitespace(dataBuffer[j++])) {
	}
	dataBuffer[i++] = ' ';
	dataBuffer[i++] = dataBuffer[j-1];
      } else {
	dataBuffer[i++] = c;
      }
    }

				// The new length is <= the old one.
    dataBufferPos = i;
  }


  /**
    * Convert the data buffer to a string.
    * @param internFlag true if the contents should be interned.
    * @see #intern(char[],int,int)
    */
  String dataBufferToString ()
  {
    String s = new String(dataBuffer, 0, dataBufferPos);
    dataBufferPos = 0;
    return s;
  }


  /**
    * Flush the contents of the data buffer to the handler, if
    * appropriate, and reset the buffer for new input.
    */
  void dataBufferFlush ()
    throws java.lang.Exception
  {
    if (dataBufferPos > 0) {
      switch (currentElementContent) {
      case CONTENT_UNDECLARED:
      case CONTENT_EMPTY:
	// do nothing
	break;
      case CONTENT_MIXED:
      case CONTENT_ANY:
	if (handler != null) {
	  handler.charData(dataBuffer, 0, dataBufferPos);
	}
	break;
      case CONTENT_ELEMENTS:
	if (handler != null) {
	  handler.ignorableWhitespace(dataBuffer, 0, dataBufferPos);
	}
	break;
      }
      dataBufferPos = 0;
    }
  }


  /**
    * Require a string to appear, or throw an exception.
    */
  void require (String delim)
    throws java.lang.Exception
  {
    char ch[] = delim.toCharArray();
    for (int i = 0; i < ch.length; i++) {
      require(ch[i]);
    }
  }


  /**
    * Require a character to appear, or throw an exception.
    */
  void require (char delim)
       throws java.lang.Exception
  {
    char c = readCh();

    if (c != delim) {
      error("expected character", c, new Character(delim).toString());
    }
  }


  /**
    * Return an internalised version of a string.
    * <p>&AElig;lfred uses this method to create an internalised version
    * of all names and attribute values, so that it can test equality
    * with <code>==</code> instead of <code>String.equals()</code>.
    * <p>If you want to be able to test for equality in the same way,
    * you can use this method to internalise your own strings first:
    * <pre>
    * String PARA = handler.intern("PARA");
    * </pre>
    * <p>Note that this will not return the same results as String.intern().
    * @param s The string to internalise.
    * @return An internalised version of the string.
    * @see #intern(char[],int,int)
    * @see java.lang.String#intern
    */
  public String intern (String s)
  {
    char ch[] = s.toCharArray();
    return intern(ch, 0, ch.length);
  }


  /**
    * Create an internalised string from a character array.
    * <p>This is much more efficient than constructing a non-internalised
    * string first, and then internalising it.
    * <p>Note that this will not return the same results as String.intern().
    * @param ch an array of characters for building the string.
    * @param start the starting position in the array.
    * @param length the number of characters to place in the string.
    * @return an internalised string.
    * @see #intern(String)
    * @see java.lang.String#intern
    */
  public String intern (char ch[], int start, int length)
  {
    int index;
    int hash = 0;

				// Generate a hash code.
    for (int i = start; i < start + length; i++) {
      hash = ((hash << 1) & 0xffffff) + (int)ch[i];
    }

    hash = hash % SYMBOL_TABLE_LENGTH;

				// Get the bucket.
    Object bucket[] = (Object[])symbolTable[hash];
    if (bucket == null) {
      symbolTable[hash] = bucket = new Object[8];
    }

				// Search for a matching tuple, and
				// return the string if we find one.
    for (index = 0; index < bucket.length; index += 2) {
      char chFound[] = (char[])bucket[index];

				// Stop when we hit a null index.
      if (chFound == null) {
	break;
      }

				// If they're the same length,
				// check for a match.
				// If the loop finishes, 'index' will
				// contain the current bucket
				// position.
      if (chFound.length == length) {
	for (int i = 0; i < chFound.length; i++) {
				// Stop if there are no more tuples.
	  if (ch[start+i] != chFound[i]) {
	    break;
	  } else if (i == length-1) {
				// That's it, we have a match!
	    return (String)bucket[index+1];
	  }
	}
      }
    }

				// Not found -- we'll have to add it.

				// Do we have to grow the bucket?
    bucket =
      (Object[])extendArray(bucket, bucket.length, index);

				// OK, add it to the end of the
				// bucket.
    String s = new String(ch, start, length);
    bucket[index] = s.toCharArray();
    bucket[index+1] = s;
    symbolTable[hash] = bucket;
    return s;
  }


  /**
    * Ensure the capacity of an array, allocating a new one if
    * necessary.
    */
  Object extendArray (Object array, int currentSize, int requiredSize)
  {
    if (requiredSize < currentSize) {
      return array;
    } else {
      Object newArray = null;
      int newSize = currentSize * 2;

      if (newSize <= requiredSize) {
	newSize = requiredSize + 1;
      }

      if (array instanceof char[]) {
	newArray = new char[newSize];
      } else if (array instanceof Object[]) {
	newArray = new Object[newSize];
      }

      System.arraycopy(array, 0, newArray, 0, currentSize);
      return newArray;
    }
  }



  //////////////////////////////////////////////////////////////////////
  // XML query routines.
  //////////////////////////////////////////////////////////////////////


  //
  // Elements
  //

  /**
    * Get the declared elements for an XML document.
    * <p>The results will be valid only after the DTD (if any) has been
    * parsed.
    * @return An enumeration of all element types declared for this
    *         document (as Strings).
    * @see #getElementContentType
    * @see #getElementContentModel
    */
  public Enumeration declaredElements ()
  {
    return elementInfo.keys();
  }


  /**
    * Look up the content type of an element.
    * @param name The element type name.
    * @return An integer constant representing the content type.
    * @see #getElementContentModel
    * @see #CONTENT_UNDECLARED
    * @see #CONTENT_ANY
    * @see #CONTENT_EMPTY
    * @see #CONTENT_MIXED
    * @see #CONTENT_ELEMENTS
    */
  public int getElementContentType (String name)
  {
    Object element[] = (Object[])elementInfo.get(name);
    if (element == null) {
      return CONTENT_UNDECLARED;
    } else {
      return ((Integer)element[0]).intValue();
    }
  }


  /**
    * Look up the content model of an element.
    * <p>The result will always be null unless the content type is
    * CONTENT_ELEMENTS or CONTENT_MIXED.
    * @param name The element type name.
    * @return The normalised content model, as a string.
    * @see #getElementContentType
    */
  public String getElementContentModel (String name)
  {
    Object element[] = (Object[])elementInfo.get(name);
    if (element == null) {
      return null;
    } else {
      return (String)element[1];
    }
  }


  /**
    * Register an element.
    * Array format:
    *  element type
    *  attribute hash table
    */
  void setElement (String name, int contentType,
		   String contentModel, Hashtable attributes)
    throws java.lang.Exception
  {
    Object element[];

				// Try looking up the element
    element = (Object[])elementInfo.get(name);

				// Make a new one if necessary.
    if (element == null) {
      element = new Object[3];
      element[0] = new Integer(CONTENT_UNDECLARED);
      element[1] = null;
      element[2] = null;
    } else if (contentType != CONTENT_UNDECLARED &&
	       ((Integer)element[0]).intValue() != CONTENT_UNDECLARED) {
      error("multiple declarations for element type", name, null);
      return;
    }

				// Insert the content type, if any.
    if (contentType != CONTENT_UNDECLARED) {
      element[0] = new Integer(contentType);
    }

				// Insert the content model, if any.
    if (contentModel != null) {
      element[1] = contentModel;
    }

				// Insert the attributes, if any.
    if (attributes != null) {
      element[2] =attributes;
    }

				// Save the element info.
    elementInfo.put(name,element);
  }


  /**
    * Look up the attribute hash table for an element.
    * The hash table is the second item in the element array.
    */
  Hashtable getElementAttributes (String name)
  {
    Object element[] = (Object[])elementInfo.get(name);
    if (element == null) {
      return null;
    } else {
      return (Hashtable)element[2];
    }
  }



  //
  // Attributes
  //

  /**
    * Get the declared attributes for an element type.
    * @param elname The name of the element type.
    * @return An Enumeration of all the attributes declared for
    *         a specific element type.  The results will be valid only
    *         after the DTD (if any) has been parsed.
    * @see #getAttributeType
    * @see #getAttributeEnumeration
    * @see #getAttributeDefaultValueType
    * @see #getAttributeDefaultValue
    * @see #getAttributeExpandedValue
    */
  public Enumeration declaredAttributes (String elname)
  {
    Hashtable attlist = getElementAttributes(elname);

    if (attlist == null) {
      return null;
    } else {
      return attlist.keys();
    }
  }


  /**
    * Retrieve the declared type of an attribute.
    * @param name The name of the associated element.
    * @param aname The name of the attribute.
    * @return An integer constant representing the attribute type.
    * @see #ATTRIBUTE_UNDECLARED
    * @see #ATTRIBUTE_CDATA
    * @see #ATTRIBUTE_ID
    * @see #ATTRIBUTE_IDREF
    * @see #ATTRIBUTE_IDREFS
    * @see #ATTRIBUTE_ENTITY
    * @see #ATTRIBUTE_ENTITIES
    * @see #ATTRIBUTE_NMTOKEN
    * @see #ATTRIBUTE_NMTOKENS
    * @see #ATTRIBUTE_ENUMERATED
    * @see #ATTRIBUTE_NOTATION
    */
  public int getAttributeType (String name, String aname)
  {
    Object attribute[] = getAttribute(name, aname);
    if (attribute == null) {
      return ATTRIBUTE_UNDECLARED;
    } else {
      return ((Integer)attribute[0]).intValue();
    }
  }


  /**
    * Retrieve the allowed values for an enumerated attribute type.
    * @param name The name of the associated element.
    * @param aname The name of the attribute.
    * @return A string containing the token list.
    * @see #ATTRIBUTE_ENUMERATED
    * @see #ATTRIBUTE_NOTATION
    */
  public String getAttributeEnumeration (String name, String aname)
  {
    Object attribute[] = getAttribute(name, aname);
    if (attribute == null) {
      return null;
    } else {
      return (String)attribute[3];
    }
  }


  /**
    * Retrieve the default value of a declared attribute.
    * @param name The name of the associated element.
    * @param aname The name of the attribute.
    * @return The default value, or null if the attribute was
    *         #IMPLIED or simply undeclared and unspecified.
    * @see #getAttributeExpandedValue
    */
  public String getAttributeDefaultValue (String name, String aname)
  {
    Object attribute[] = getAttribute(name, aname);
    if (attribute == null) {
      return null;
    } else {
      return (String)attribute[1];
    }
  }


  /**
    * Retrieve the expanded value of a declared attribute.
    * <p>All general entities will be expanded.
    * @param name The name of the associated element.
    * @param aname The name of the attribute.
    * @return The expanded default value, or null if the attribute was
    *         #IMPLIED or simply undeclared
    * @see #getAttributeDefaultValue
    */
  public String getAttributeExpandedValue (String name, String aname)
  {
    Object attribute[] = getAttribute(name, aname);
    if (attribute == null) {
      return null;
    } else if (attribute[4] == null && attribute[1] != null) {
      try {
	pushString(null, (char)0 + (String)attribute[1] + (char)0);
	attribute[4] = readLiteral(LIT_NORMALIZE |
				   LIT_CHAR_REF |
				   LIT_ENTITY_REF);
      } catch (Exception e) {}
    }
    return (String)attribute[4];
  }


  /**
    * Retrieve the default value type of a declared attribute.
    * @see #ATTRIBUTE_DEFAULT_SPECIFIED
    * @see #ATTRIBUTE_DEFAULT_IMPLIED
    * @see #ATTRIBUTE_DEFAULT_REQUIRED
    * @see #ATTRIBUTE_DEFAULT_FIXED
    */
  public int getAttributeDefaultValueType (String name, String aname)
  {
    Object attribute[] = getAttribute(name, aname);
    if (attribute == null) {
      return ATTRIBUTE_DEFAULT_UNDECLARED;
    } else {
      return ((Integer)attribute[2]).intValue();
    }
  }


  /**
    * Register an attribute declaration for later retrieval.
    * Format:
    * - String type
    * - String default value
    * - int value type
    * *TODO: do something with attribute types.
    */
  void setAttribute (String elName, String name, int type, String enumeration,
		     String value, int valueType)
    throws java.lang.Exception
  {
    Hashtable attlist;
    Object attribute[];

				// Create a new hashtable if necessary.
    attlist = getElementAttributes(elName);
    if (attlist == null) {
      attlist = new Hashtable();
    }

				// Check that the attribute doesn't
				// already exist!
    if (attlist.get(name) != null) {
      return;
    } else {
      attribute = new Object[5];
      attribute[0] = new Integer(type);
      attribute[1] = value;
      attribute[2] = new Integer(valueType);
      attribute[3] = enumeration;
      attribute[4] = null;
      attlist.put(name.intern(), attribute);

				// Use CONTENT_UNDECLARED to avoid overwriting
				// existing element declaration.
      setElement(elName,CONTENT_UNDECLARED, null, attlist);
    }
  }


  /**
    * Retrieve the three-member array representing an
    * attribute declaration.
    */
  Object[] getAttribute (String elName, String name)
  {
    Hashtable attlist;
    Object attribute[];

    attlist = getElementAttributes(elName);
    if (attlist == null) {
      return null;
    }

    attribute = (Object[])attlist.get(name);
    return attribute;
  }


  //
  // Entities
  //

  /**
    * Get declared entities.
    * @return An Enumeration of all the entities declared for
    *         this XML document.  The results will be valid only
    *         after the DTD (if any) has been parsed.
    * @see #getEntityType
    * @see #getEntityPublicId
    * @see #getEntitySystemId
    * @see #getEntityValue
    * @see #getEntityNotationName
    */
  public Enumeration declaredEntities ()
  {
    return entityInfo.keys();
  }


  /**
    * Find the type of an entity.
    * @return An integer constant representing the entity type.
    * @see #ENTITY_UNDECLARED
    * @see #ENTITY_INTERNAL
    * @see #ENTITY_NDATA
    * @see #ENTITY_TEXT
    */
  public int getEntityType (String ename)
  {
    Object entity[] = (Object[])entityInfo.get(ename);
    if (entity == null) {
      return ENTITY_UNDECLARED;
    } else {
      return ((Integer)entity[0]).intValue();
    }
  }


  /**
    * Return an external entity's public identifier, if any.
    * @param ename The name of the external entity.
    * @return The entity's system identifier, or null if the
    *         entity was not declared, if it is not an
    *         external entity, or if no public identifier was
    *         provided.
    * @see #getEntityType
    */
  public String getEntityPublicId (String ename)
  {
    Object entity[] = (Object[])entityInfo.get(ename);
    if (entity == null) {
      return null;
    } else {
      return (String)entity[1];
    }
  }


  /**
    * Return an external entity's system identifier.
    * @param ename The name of the external entity.
    * @return The entity's system identifier, or null if the
    *         entity was not declared, or if it is not an
    *         external entity.
    * @see #getEntityType
    */
  public String getEntitySystemId (String ename)
  {
    Object entity[] = (Object[])entityInfo.get(ename);
    if (entity == null) {
      return null;
    } else {
      return (String)entity[2];
    }
  }


  /**
    * Return the value of an internal entity.
    * @param ename The name of the internal entity.
    * @return The entity's value, or null if the entity was
    *         not declared, or if it is not an internal entity.
    * @see #getEntityType
    */
  public String getEntityValue (String ename)
  {
    Object entity[] = (Object[])entityInfo.get(ename);
    if (entity == null) {
      return null;
    } else {
      return (String)entity[3];
    }
  }


  /**
    * Get the notation name associated with an NDATA entity.
    * @param eName The NDATA entity name.
    * @return The associated notation name, or null if the
    *         entity was not declared, or if it is not an
    *         NDATA entity.
    * @see #getEntityType
    */
  public String getEntityNotationName (String eName)
  {
    Object entity[] = (Object[])entityInfo.get(eName);
    if (entity == null) {
      return null;
    } else {
      return (String)entity[4];
    }
  }


  /**
    * Register an entity declaration for later retrieval.
    */
  void setInternalEntity (String eName, String value)
  {
    setEntity(eName, ENTITY_INTERNAL, null, null, value, null);
  }


  /**
    * Register an external data entity.
    */
  void setExternalDataEntity (String eName, String pubid,
			      String sysid, String nName)
  {
    setEntity(eName, ENTITY_NDATA, pubid, sysid, null, nName);
  }


  /**
    * Register an external text entity.
    */
  void setExternalTextEntity (String eName, String pubid, String sysid)
  {
    setEntity(eName, ENTITY_TEXT, pubid, sysid, null, null);
  }


  /**
    * Register an entity declaration for later retrieval.
    */
  void setEntity (String eName, int eClass,
		  String pubid, String sysid,
		  String value, String nName)
  {
    Object entity[];

    if (entityInfo.get(eName) == null) {
      entity = new Object[5];
      entity[0] = new Integer(eClass);
      entity[1] = pubid;
      entity[2] = sysid;
      entity[3] = value;
      entity[4] = nName;

      entityInfo.put(eName,entity);
    }
  }


  //
  // Notations.
  //

  /**
    * Get declared notations.
    * @return An Enumeration of all the notations declared for
    *         this XML document.  The results will be valid only
    *         after the DTD (if any) has been parsed.
    * @see #getNotationPublicId
    * @see #getNotationSystemId
    */
  public Enumeration declaredNotations ()
  {
    return notationInfo.keys();
  }


  /**
    * Look up the public identifier for a notation.
    * You will normally use this method to look up a notation
    * that was provided as an attribute value or for an NDATA entity.
    * @param nname The name of the notation.
    * @return A string containing the public identifier, or null
    *         if none was provided or if no such notation was
    *         declared.
    * @see #getNotationSystemId
    */
  public String getNotationPublicId (String nname)
  {
    Object notation[] = (Object[])notationInfo.get(nname);
    if (notation == null) {
      return null;
    } else {
      return (String)notation[0];
    }
  }


  /**
    * Look up the system identifier for a notation.
    * You will normally use this method to look up a notation
    * that was provided as an attribute value or for an NDATA entity.
    * @param nname The name of the notation.
    * @return A string containing the system identifier, or null
    *         if no such notation was declared.
    * @see #getNotationPublicId
    */
  public String getNotationSystemId (String nname)
  {
    Object notation[] = (Object[])notationInfo.get(nname);
    if (notation == null) {
      return null;
    } else {
      return (String)notation[1];
    }
  }


  /**
    * Register a notation declaration for later retrieval.
    * Format:
    * - public id
    * - system id
    */
  void setNotation (String nname, String pubid, String sysid)
    throws java.lang.Exception
  {
    Object notation[];

    if (notationInfo.get(nname) == null) {
      notation = new Object[2];
      notation[0] = pubid;
      notation[1] = sysid;
      notationInfo.put(nname,notation);
    } else {
      error("multiple declarations of notation", nname, null);
    }
  }


  //
  // Location.
  //


  /**
    * Return the current line number.
    */
  public int getLineNumber ()
  {
    return line;
  }


  /**
    * Return the current column number.
    */
  public int getColumnNumber ()
  {
    return column;
  }



  //////////////////////////////////////////////////////////////////////
  // High-level I/O.
  //////////////////////////////////////////////////////////////////////


  /**
    * Read a single character from the readBuffer.
    * <p>The readDataChunk() method maintains the buffer.
    * <p>If we hit the end of an entity, try to pop the stack and
    * keep going.
    * <p>(This approach doesn't really enforce XML's rules about
    * entity boundaries, but this is not currently a validating
    * parser).
    * <p>This routine also attempts to keep track of the current
    * position in external entities, but it's not entirely accurate.
    * @return The next available input character.
    * @see #unread(char)
    * @see #unread(String)
    * @see #readDataChunk
    * @see #readBuffer
    * @see #line
    * @return The next character from the current input source.
    */
  char readCh ()
    throws java.lang.Exception
    {
    char c;

    // As long as there's nothing in the
    // read buffer, try reading more data
    // (for an external entity) or popping
    // the entity stack (for either).
    while (readBufferPos >= readBufferLength)
      {
      switch (sourceType)
        {
        case INPUT_READER:
        case INPUT_EXTERNAL:
        case INPUT_STREAM:
        readDataChunk();
        while (readBufferLength < 1)
          {
          popInput();
          if (readBufferLength <1)
            {
            readDataChunk();
            }
          }
        break;

        default:
        popInput();
        break;
        }
      }

    c = readBuffer[readBufferPos++];

    // This is a particularly nasty bit
    // of code, that checks for a parameter
    // entity reference but peeks ahead to
    // catch the '%' in parameter entity
    // declarations.
    if
      (
      c == '%' && 
      (context == CONTEXT_DTD || context == CONTEXT_ENTITYVALUE)
      )
      {
      char c2 = readCh();
      unread(c2);
      if (!isWhitespace(c2))
        {
        parsePEReference(context == CONTEXT_ENTITYVALUE);
        return readCh();
        }
      }

    if (c == '\n')
      {
      line++;
      column = 0;
      }
    else
      {
      column++;
      }

    return c;
    }


  /**
    * Push a single character back onto the current input stream.
    * <p>This method usually pushes the character back onto
    * the readBuffer, while the unread(String) method treats the
    * string as a new internal entity.
    * <p>I don't think that this would ever be called with 
    * readBufferPos = 0, because the methods always reads a character
    * before unreading it, but just in case, I've added a boundary
    * condition.
    * @param c The character to push back.
    * @see #readCh
    * @see #unread(String)
    * @see #unread(char[])
    * @see #readBuffer
    */
  void unread (char c)
    throws java.lang.Exception
    {
    // Normal condition.
    if (c == '\n')
      {
      line--;
      column = -1;
      }
    if (readBufferPos > 0)
      {
      readBuffer[--readBufferPos] = c;
      }
    else
      {
      pushString(null, new Character(c).toString());
      }
    }


  /**
    * Push a char array back onto the current input stream.
    * <p>NOTE: you must <em>never</em> push back characters that you
    * haven't actually read: use pushString() instead.
    * @see #readCh
    * @see #unread(char)
    * @see #unread(String)
    * @see #readBuffer
    * @see #pushString
    */
  void unread (char ch[], int length) 
    throws java.lang.Exception
    {
    for (int i = 0; i < length; i++)
        {
        if (ch[i] == '\n')
          {line--;column = -1;}
        }
    if (length < readBufferPos)
      {readBufferPos -= length;}
    else
      {
      pushCharArray(null, ch, 0, length);
      sourceType = INPUT_BUFFER;
      }
    }


  /**
    * Push a new external input source.
    * <p>The source will be either an external text entity, or the DTD
    * external subset.
    * <p>TO DO: Right now, this method always attempts to autodetect
    * the encoding; in the future, it should allow the caller to 
    * request an encoding explicitly, and it should also look at the
    * headers with an HTTP connection.
    * @param url The java.net.URL object for the entity.
    * @see XmlHandler#resolveEntity
    * @see #pushString
    * @see #sourceType
    * @see #pushInput
    * @see #detectEncoding
    * @see #sourceType
    * @see #readBuffer
    */
  void pushURL (String ename, String publicId, String systemId,
		Reader reader, InputStream stream, String encoding)
    throws java.lang.Exception
  {
    URL url;
    boolean ignoreEncoding = false;

				// Push the existing status.
    pushInput(ename);

				// Create a new read buffer.
				// (Note the four-character margin)
    readBuffer = new char[READ_BUFFER_MAX+4];
    readBufferPos = 0;
    readBufferLength = 0;
    readBufferOverflow = -1;
    is = null;
    line = 1;

    currentByteCount = 0;

				// Flush any remaining data.
    dataBufferFlush();

				// Make the URL absolute.
    if (systemId != null && externalEntity != null) {
      systemId = new URL(externalEntity.getURL(), systemId).toString();
    } else if (baseURI != null) {
      try {
	systemId = new URL(new URL(baseURI), systemId).toString();
      } catch (Exception e) {}
    }

				// See if the application wants to
				// redirect the system ID and/or
				// supply its own character stream.
    if (systemId != null && handler != null) {
      Object input = handler.resolveEntity(publicId, systemId);
      if (input != null) {
	if (input instanceof String) {
	  systemId = (String)input;
	} else if (input instanceof InputStream) {
	  stream = (InputStream)input;
	} else if (input instanceof Reader) {
	  reader = (Reader)input;
	}
      }
    }

				// Start the entity.
    if (handler != null) {
      if (systemId != null) {
	handler.startExternalEntity(systemId);
      } else {
	handler.startExternalEntity("[external stream]");
      }
    }

				// Figure out what we're reading from.
    if (reader != null) {
				// There's an explicit character stream.
      sourceType = INPUT_READER;
      this.reader = reader;
      tryEncodingDecl(true);
      return;
    } else if (stream != null) {
      sourceType = INPUT_STREAM;
      is = stream;
    } else {
				// We have to open our own stream
				// to the URL.

				// Set the new status
      sourceType = INPUT_EXTERNAL;
      url = new URL(systemId);

      externalEntity = url.openConnection();
      externalEntity.connect();
      is = externalEntity.getInputStream();
    }

				// If we get to here, there must be
				// an InputStream available.
    if (!is.markSupported()) {
      is = new BufferedInputStream(is);
    }

				// Attempt to detect the encoding.
    if (encoding == null && externalEntity != null) {
      encoding = externalEntity.getContentEncoding();
    }

    if (encoding != null) {
      checkEncoding(encoding, false);
      ignoreEncoding = true;
    } else {
      detectEncoding();
      ignoreEncoding = false;
    }

				// Read an XML or text declaration.
    tryEncodingDecl(ignoreEncoding);
  }


  /**
    * Check for an encoding declaration.
    */
  void tryEncodingDecl (boolean ignoreEncoding)
    throws java.lang.Exception
  {
				// Read the XML/Encoding declaration.
    if (tryRead("<?xml")) {
      if (tryWhitespace()) {
	if (inputStack.size() > 0) {
	  parseTextDecl(ignoreEncoding);
	} else {
	  parseXMLDecl(ignoreEncoding);
	}
      } else {
	unread("xml".toCharArray(), 3);
	parsePI();
      }
    }
  }


  /**
    * Attempt to detect the encoding of an entity.
    * <p>The trick here (as suggested in the XML standard) is that
    * any entity not in UTF-8, or in UCS-2 with a byte-order mark, 
    * <b>must</b> begin with an XML declaration or an encoding
    * declaration; we simply have to look for "&lt;?XML" in various
    * encodings.
    * <p>This method has no way to distinguish among 8-bit encodings.
    * Instead, it assumes UTF-8, then (possibly) revises its assumption
    * later in checkEncoding().  Any ASCII-derived 8-bit encoding
    * should work, but most will be rejected later by checkEncoding().
    * <p>I don't currently detect EBCDIC, since I'm concerned that it
    * could also be a valid UTF-8 sequence; I'll have to do more checking
    * later.
    * @see #tryEncoding(byte[], byte, byte, byte, byte)
    * @see #tryEncoding(byte[], byte, byte)
    * @see #checkEncoding
    * @see #read8bitEncodingDeclaration
    */
  void detectEncoding ()
    throws java.lang.Exception
  {
    byte signature[] = new byte[4];

				// Read the first four bytes for
				// autodetection.
    is.mark(4);
    is.read(signature);
    is.reset();

				// Look for a known signature.
    if (tryEncoding(signature, (byte)0x00, (byte)0x00,
		    (byte)0x00, (byte)0x3c)) {
      // UCS-4 must begin with "<!XML"
      // 0x00 0x00 0x00 0x3c: UCS-4, big-endian (1234)
      encoding = ENCODING_UCS_4_1234;
    } else if (tryEncoding(signature, (byte)0x3c, (byte)0x00,
			   (byte)0x00, (byte)0x00)) {
      // UCS-4 must begin with "<!XML"
      // 0x3c 0x00 0x00 0x00: UCS-4, little-endian (4321)
      encoding = ENCODING_UCS_4_4321;
    } else if (tryEncoding(signature, (byte)0x00, (byte)0x00,
			   (byte)0x3c, (byte)0x00)) {
      // UCS-4 must begin with "<!XML"
      // 0x00 0x00 0x3c 0x00: UCS-4, unusual (2143)
      encoding = ENCODING_UCS_4_2143;
    } else if (tryEncoding(signature, (byte)0x00, (byte)0x3c,
			   (byte)0x00, (byte)0x00)) {
      // UCS-4 must begin with "<!XML"
      // 0x00 0x3c 0x00 0x00: UCS-4, unusual (3421)
      encoding = ENCODING_UCS_4_3412;
    } else if (tryEncoding(signature, (byte)0xfe, (byte)0xff)) {
      // UCS-2 with a byte-order marker.
      // 0xfe 0xff: UCS-2, big-endian (12)
      encoding = ENCODING_UCS_2_12;
      is.read(); is.read();
    } else if (tryEncoding(signature, (byte)0xff, (byte)0xfe)) {
      // UCS-2 with a byte-order marker.
      // 0xff 0xfe: UCS-2, little-endian (21)
      encoding = ENCODING_UCS_2_21;
      is.read(); is.read();
    } else if (tryEncoding(signature, (byte)0x00, (byte)0x3c,
			   (byte)0x00, (byte)0x3f)) {
      // UCS-2 without a BOM must begin with "<?XML"
      // 0x00 0x3c 0x00 0x3f: UCS-2, big-endian, no byte-order mark
      encoding = ENCODING_UCS_2_12;
      error("no byte-order mark for UCS-2 entity", null, null);
    } else if (tryEncoding(signature, (byte)0x3c, (byte)0x00,
			   (byte)0x3f, (byte)0x00)) {
      // UCS-2 without a BOM must begin with "<?XML"
      // 0x3c 0x00 0x3f 0x00: UCS-2, little-endian, no byte-order mark
      encoding = ENCODING_UCS_2_21;
      error("no byte-order mark for UCS-2 entity", null, null);
    } else if (tryEncoding(signature, (byte)0x3c, (byte)0x3f,
			   (byte)0x78, (byte)0x6d)) {
      // Some kind of 8-bit encoding with "<?XML"
      // 0x3c 0x3f 0x78 0x6d: UTF-8 or other 8-bit markup (read ENCODING)
      encoding = ENCODING_UTF_8;
      read8bitEncodingDeclaration();
    } else {
      // Some kind of 8-bit encoding without "<?XML"
      // (otherwise) UTF-8 without encoding/XML declaration
      encoding = ENCODING_UTF_8;
    }
  }


  /**
    * Check for a four-byte signature.
    * <p>Utility routine for detectEncoding().
    * <p>Always looks for some part of "<?XML" in a specific encoding.
    * @param sig The first four bytes read.
    * @param b1 The first byte of the signature
    * @param b2 The second byte of the signature
    * @param b3 The third byte of the signature
    * @param b4 The fourth byte of the signature
    * @see #detectEncoding
    */
  boolean tryEncoding (byte sig[], byte b1, byte b2, byte b3, byte b4)
  {
    return (sig[0] == b1 && sig[1] == b2 && sig[2] == b3 && sig[3] == b4);
  }


  /**
    * Check for a two-byte signature.
    * <p>Looks for a UCS-2 byte-order mark.
    * <p>Utility routine for detectEncoding().
    * @param sig The first four bytes read.
    * @param b1 The first byte of the signature
    * @param b2 The second byte of the signature
    * @see #detectEncoding
    */
  boolean tryEncoding (byte sig[], byte b1, byte b2)
  {
    return ((sig[0] == b1) && (sig[1] == b2));
  }


  /**
    * This method pushes a string back onto input.
    * <p>It is useful either as the expansion of an internal entity, 
    * or for backtracking during the parse.
    * <p>Call pushCharArray() to do the actual work.
    * @param s The string to push back onto input.
    * @see #pushCharArray
    */
  void pushString (String ename, String s) 
    throws java.lang.Exception
  {
    char ch[] = s.toCharArray();
    pushCharArray(ename, ch, 0, ch.length);
  }


  /**
    * Push a new internal input source.
    * <p>This method is useful for expanding an internal entity,
    * or for unreading a string of characters.  It creates a new
    * readBuffer containing the characters in the array, instead
    * of characters converted from an input byte stream.
    * <p>I've added a couple of optimisations: don't push zero-
    * length strings, and just push back a single character
    * for 1-character strings; this should save some time and memory.
    * @param ch The char array to push.
    * @see #pushString
    * @see #pushURL
    * @see #readBuffer
    * @see #sourceType
    * @see #pushInput
    */
  void pushCharArray (String ename, char ch[], int start, int length)
    throws java.lang.Exception
  {
				// Push the existing status
    pushInput(ename);
    sourceType = INPUT_INTERNAL;
    readBuffer = ch;
    readBufferPos = start;
    readBufferLength = length;
    readBufferOverflow = -1;
  }


  /**
    * Save the current input source onto the stack.
    * <p>This method saves all of the global variables associated with
    * the current input source, so that they can be restored when a new
    * input source has finished.  It also tests for entity recursion.
    * <p>The method saves the following global variables onto a stack
    * using a fixed-length array:
    * <ol>
    * <li>sourceType
    * <li>externalEntity
    * <li>readBuffer
    * <li>readBufferPos
    * <li>readBufferLength
    * <li>line
    * <li>encoding
    * </ol>
    * @param ename The name of the entity (if any) causing the new input.
    * @see #popInput
    * @see #sourceType
    * @see #externalEntity
    * @see #readBuffer
    * @see #readBufferPos
    * @see #readBufferLength
    * @see #line
    * @see #encoding
    */
  void pushInput (String ename)
    throws java.lang.Exception
  {
    Object input[] = new Object[12];

				// Check for entity recursion.
    if (ename != null) {
      Enumeration entities = entityStack.elements();
      while (entities.hasMoreElements()) {
	String e = (String)entities.nextElement();
	if (e == ename) {
	  error("recursive reference to entity", ename, null);
	}
      }
    }
    entityStack.push(ename);

				// Don't bother if there is no input.
    if (sourceType == INPUT_NONE) {
      return;
    }

				// Set up a snapshot of the current
				// input source.
    input[0] = new Integer(sourceType);
    input[1] = externalEntity;
    input[2] = readBuffer;
    input[3] = new Integer(readBufferPos);
    input[4] = new Integer(readBufferLength);
    input[5] = new Integer(line);
    input[6] = new Integer(encoding);
    input[7] = new Integer(readBufferOverflow);
    input[8] = is;
    input[9] = new Integer(currentByteCount);
    input[10] = new Integer(column);
    input[11] = reader;

				// Push it onto the stack.
    inputStack.push(input);
  }


  /**
    * Restore a previous input source.
    * <p>This method restores all of the global variables associated with
    * the current input source.
    * @exception java.io.EOFException
    *    If there are no more entries on the input stack.
    * @see #pushInput
    * @see #sourceType
    * @see #externalEntity
    * @see #readBuffer
    * @see #readBufferPos
    * @see #readBufferLength
    * @see #line
    * @see #encoding
    */
  void popInput ()
    throws java.lang.Exception
  {
    Object input[];


    switch (sourceType) {

    case INPUT_EXTERNAL:
      dataBufferFlush();
      if (handler != null && externalEntity != null) {
	handler.endExternalEntity(externalEntity.getURL().toString());
      }
      break;
    case INPUT_STREAM:
      dataBufferFlush();
      if (baseURI != null) {
	if (handler != null) {
	  handler.endExternalEntity(baseURI);
	}
      }
      break;
    case INPUT_READER:
      dataBufferFlush();
      if (baseURI != null) {
	if (handler != null) {
	  handler.endExternalEntity(baseURI);
	}
      }
      break;
    }

				// Throw an EOFException if there
				// is nothing else to pop.
    if (inputStack.isEmpty()) {
      throw new EOFException();
    } else {
      String s;
      input = (Object[])inputStack.pop();
      s = (String)entityStack.pop();
    }

    sourceType = ((Integer)input[0]).intValue();
    externalEntity = (URLConnection)input[1];
    readBuffer = (char[])input[2];
    readBufferPos = ((Integer)input[3]).intValue();
    readBufferLength = ((Integer)input[4]).intValue();
    line = ((Integer)input[5]).intValue();
    encoding = ((Integer)input[6]).intValue();
    readBufferOverflow = ((Integer)input[7]).intValue();
    is = (InputStream)input[8];
    currentByteCount = ((Integer)input[9]).intValue();
    column = ((Integer)input[10]).intValue();
    reader = (Reader)input[11];
  }


  /**
    * Return true if we can read the expected character.
    * <p>Note that the character will be removed from the input stream
    * on success, but will be put back on failure.  Do not attempt to
    * read the character again if the method succeeds.
    * @param delim The character that should appear next.  For a
    *              insensitive match, you must supply this in upper-case.
    * @return true if the character was successfully read, or false if
    *         it was not.
    * @see #tryRead(String)
    */
  boolean tryRead (char delim)
    throws java.lang.Exception
  {
    char c;

				// Read the character
    c = readCh();

				// Test for a match, and push the character
				// back if the match fails.
    if (c == delim) {
      return true;
    } else {
      unread(c);
      return false;
    }
  }


  /**
    * Return true if we can read the expected string.
    * <p>This is simply a convenience method.
    * <p>Note that the string will be removed from the input stream
    * on success, but will be put back on failure.  Do not attempt to
    * read the string again if the method succeeds.
    * <p>This method will push back a character rather than an
    * array whenever possible (probably the majority of cases).
    * <p><b>NOTE:</b> This method currently has a hard-coded limit
    * of 100 characters for the delimiter.
    * @param delim The string that should appear next.
    * @return true if the string was successfully read, or false if
    *         it was not.
    * @see #tryRead(char)
    */
  boolean tryRead (String delim)
    throws java.lang.Exception
    {
    char ch[] = delim.toCharArray();
    char c;

    // Compare the input, character-
    // by character.
    
    for (int i = 0; i < ch.length; i++)
      {
      c=readCh();
      if (c!=ch[i])
        {
        unread(c);
        if (i!=0)
          {unread(ch,i);}
        return false;
        }
      }
    return true;
    }



  /**
    * Return true if we can read some whitespace.
    * <p>This is simply a convenience method.
    * <p>This method will push back a character rather than an
    * array whenever possible (probably the majority of cases).
    * @return true if whitespace was found.
    */
  boolean tryWhitespace ()
    throws java.lang.Exception
  {
    char c;
    c = readCh();
    if (isWhitespace(c)) {
      skipWhitespace();
      return true;
    } else {
      unread(c);
      return false;
    }
  }


  /**
    * Read all data until we find the specified string.
    * <p>This is especially useful for scanning marked sections.
    * <p>This is a a little inefficient right now, since it calls tryRead()
    * for every character.
    * @param delim The string delimiter
    * @see #tryRead(String, boolean)
    * @see #readCh
    */
  void parseUntil (String delim)
    throws java.lang.Exception
  {
    char c;
    int startLine = line;

    try {
      while (!tryRead(delim)) {
	c = readCh();
	dataBufferAppend(c);
      }
    } catch (EOFException e) {
      error("end of input while looking for delimiter (started on line " +
	    startLine + ')', null, delim);
    }
  }


  /**
    * Skip all data until we find the specified string.
    * <p>This is especially useful for scanning comments.
    * <p>This is a a little inefficient right now, since it calls tryRead()
    * for every character.
    * @param delim The string delimiter
    * @see #tryRead(String, boolean)
    * @see #readCh
    */
  void skipUntil (String delim)
    throws java.lang.Exception
  {
    while (!tryRead(delim)) {
      readCh();
    }
  }


  /**
    * Read just the encoding declaration (or XML declaration) at the 
    * start of an external entity.
    * When this method is called, we know that the declaration is
    * present (or appears to be).  We also know that the entity is
    * in some sort of ASCII-derived 8-bit encoding.
    * The idea of this is to let us read what the 8-bit encoding is
    * before we've committed to converting any more of the file; the
    * XML or encoding declaration must be in 7-bit ASCII, so we're
    * safe as long as we don't go past it.
    */
  void read8bitEncodingDeclaration ()
    throws java.lang.Exception
  {
    int ch;
    readBufferPos = readBufferLength = 0;

    while (true) {
      ch = is.read();
      readBuffer[readBufferLength++] = (char)ch;
      switch (ch) {
      case (int)'>':
	return;
      case -1:
	error("end of file before end of XML or encoding declaration.",
	      null, "?>");
	return;
      }
      if (readBuffer.length == readBufferLength) {
	error("unfinished XML or encoding declaration", null, null);
      }
    }
  }



  //////////////////////////////////////////////////////////////////////
  // Low-level I/O.
  //////////////////////////////////////////////////////////////////////


  /**
    * Read a chunk of data from an external input source.
    * <p>This is simply a front-end that fills the rawReadBuffer
    * with bytes, then calls the appropriate encoding handler.
    * @see #encoding
    * @see #rawReadBuffer
    * @see #readBuffer
    * @see #filterCR
    * @see #copyUtf8ReadBuffer
    * @see #copyIso8859_1ReadBuffer
    * @see #copyUcs_2ReadBuffer
    * @see #copyUcs_4ReadBuffer
    */
  void readDataChunk ()
    throws java.lang.Exception
    {
    int count, i, j;

    // See if we have any overflow.
    if (readBufferOverflow > -1)
      {
      readBuffer[0] = (char)readBufferOverflow;
      readBufferOverflow = -1;
      readBufferPos = 1;
      sawCR = true;
      }
    else
      {
      readBufferPos = 0;
      sawCR = false;
      }

    // Special situation -- we're taking
    // input from a character stream.
    if (sourceType == INPUT_READER)
      {
      count = reader.read(readBuffer, readBufferPos, READ_BUFFER_MAX-1);
      if (count < 0)
        {readBufferLength = -1;}
      else
        {
        readBufferLength = readBufferPos+count;
        filterCR();
        sawCR = false;
        }
      return;
      }

    // Read as many bytes as possible
    // into the read buffer.
    count = is.read(rawReadBuffer, 0, READ_BUFFER_MAX);

    // Dispatch to an encoding-specific
    // reader method to populate the
    // readBuffer.
    switch (encoding)
      {
      case ENCODING_UTF_8:
      copyUtf8ReadBuffer(count);
      break;
      
      case ENCODING_ISO_8859_1:
      copyIso8859_1ReadBuffer(count);
      break;
      
      case ENCODING_UCS_2_12:
      copyUcs2ReadBuffer(count, 8, 0);
      break;
      
      case ENCODING_UCS_2_21:
      copyUcs2ReadBuffer(count, 0, 8);
      break;
      
      case ENCODING_UCS_4_1234:
      copyUcs4ReadBuffer(count, 24, 16, 8, 0);
      break;
      
      case ENCODING_UCS_4_4321:
      copyUcs4ReadBuffer(count, 0, 8, 16, 24);
      break;
      
      case ENCODING_UCS_4_2143:
      copyUcs4ReadBuffer(count, 16, 24, 0, 8);
      break;
      
      case ENCODING_UCS_4_3412:
      copyUcs4ReadBuffer(count, 8, 0, 24, 16);
      break;
      }

    // Filter out all carriage returns
    // if we've seen any.
    if (sawCR)
      {
      filterCR();
      sawCR = false;
      }
    
    // Reset the position.
    readBufferPos = 0;
    currentByteCount += count;
    }


  /**
    * Filter carriage returns in the read buffer.
    * <p>CRLF becomes LF; CR becomes LF.
    * @see #readDataChunk
    * @see #readBuffer
    * @see #readBufferOverflow
    */
  void filterCR ()
    {
    int i, j;
    
    readBufferOverflow = -1;
    
    loop: for (i = 0, j = 0; j < readBufferLength; i++, j++)
      {
      switch (readBuffer[j])
        {
        case '\r':
        if (j == readBufferLength - 1)
          {
          readBufferOverflow = '\r';
          readBufferLength--;
          break loop;
          }
        else if (readBuffer[j+1] == '\n')
          {j++;}
        readBuffer[i] = '\n';
        break;
        
        case '\n':
        default:
        readBuffer[i] = readBuffer[j];
        break;
        }
      }
    readBufferLength = i;
    }


  /**
    * Convert a buffer of UTF-8-encoded bytes into UTF-16 characters.
    * <p>When readDataChunk() calls this method, the raw bytes are in 
    * rawReadBuffer, and the final characters will appear in 
    * readBuffer.
    * <p>The tricky part of this is dealing with UTF-8 multi-byte 
    * sequences, but it doesn't seem to slow things down too much.
    * @param count The number of bytes to convert.
    * @see #readDataChunk
    * @see #rawReadBuffer
    * @see #readBuffer
    * @see #getNextUtf8Byte
    */
  void copyUtf8ReadBuffer (int count)
    throws java.lang.Exception
  {
    int i = 0;
    int j = readBufferPos;
    int b1;
    boolean isSurrogate = false;
    while (i < count) {
      b1 = rawReadBuffer[i++];
      isSurrogate = false;

				// Determine whether we are dealing
				// with a one-, two-, three-, or four-
				// byte sequence.
      if ((b1 & 0x80) == 0) {
	// 1-byte sequence: 000000000xxxxxxx = 0xxxxxxx
	readBuffer[j++] = (char)b1;
      } else if ((b1 & 0xe0) == 0xc0) {
	// 2-byte sequence: 00000yyyyyxxxxxx = 110yyyyy 10xxxxxx
	readBuffer[j++] =
	  (char)(((b1 & 0x1f) << 6) |
		 getNextUtf8Byte(i++, count));
      } else if ((b1 & 0xf0) == 0xe0) {
	// 3-byte sequence: zzzzyyyyyyxxxxxx = 1110zzzz 10yyyyyy 10xxxxxx
	readBuffer[j++] =
	  (char)(((b1 & 0x0f) << 12) |
		 (getNextUtf8Byte(i++, count) << 6) |
		 getNextUtf8Byte(i++, count));
      } else if ((b1 & 0xf8) == 0xf0) {
	// 4-byte sequence: 11101110wwwwzzzzyy + 110111yyyyxxxxxx
	//     = 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx
	// (uuuuu = wwww + 1)
	isSurrogate = true;
	int b2 = getNextUtf8Byte(i++, count);
	int b3 = getNextUtf8Byte(i++, count);
	int b4 = getNextUtf8Byte(i++, count);
	readBuffer[j++] =
	  (char)(0xd800 |
		 ((((b1 & 0x07) << 2) | ((b2 & 0x30) >> 4) - 1) << 6) |
		 ((b2 & 0x0f) << 2) |
		 ((b3 & 0x30) >> 4));
	readBuffer[j++] =
	  (char)(0xdc |
		 ((b3 & 0x0f) << 6) |
		 b4);
				// TODO: test that surrogate value is legal.
      } else {
	// Otherwise, the 8th bit may not be set in UTF-8
	encodingError("bad start for UTF-8 multi-byte sequence", b1, i);
      }
      if (readBuffer[j-1] == '\r') {
	sawCR = true;
      }
    }
				// How many characters have we read?
    readBufferLength = j;
  }


  /**
    * Return the next byte value in a UTF-8 sequence.
    * If it is not possible to get a byte from the current
    * entity, throw an exception.
    * @param pos The current position in the rawReadBuffer.
    * @param count The number of bytes in the rawReadBuffer
    * @return The significant six bits of a non-initial byte in
    *         a UTF-8 sequence.
    * @exception EOFException If the sequence is incomplete.
    */
  int getNextUtf8Byte (int pos, int count)
    throws java.lang.Exception
  {
    int val;

				// Take a character from the buffer
				// or from the actual input stream.
    if (pos < count) {
      val = rawReadBuffer[pos];
    } else {
      val = is.read();
      if (val == -1) {
	encodingError("unfinished multi-byte UTF-8 sequence at EOF", -1, pos);
      }
    }

				// Check for the correct bits at the
				// start.
    if ((val & 0xc0) != 0x80) {
      encodingError("bad continuation of multi-byte UTF-8 sequence", val,
		    pos + 1);
    }

				// Return the significant bits.
    return (val & 0x3f);
  }


  /**
    * Convert a buffer of ISO-8859-1-encoded bytes into UTF-16 characters.
    * <p>When readDataChunk() calls this method, the raw bytes are in 
    * rawReadBuffer, and the final characters will appear in 
    * readBuffer.
    * <p>This is a direct conversion, with no tricks.
    * @param count The number of bytes to convert.
    * @see #readDataChunk
    * @see #rawReadBuffer
    * @see #readBuffer
    */
  void copyIso8859_1ReadBuffer (int count)
  {
    int i, j;
    for (i = 0, j = readBufferPos; i < count; i++, j++) {
      readBuffer[j] = (char)(rawReadBuffer[i] & 0xff);
      if (readBuffer[j] == '\r') {
	sawCR = true;
      }
    }
    readBufferLength = j;
  }


  /**
    * Convert a buffer of UCS-2-encoded bytes into UTF-16 characters.
    * <p>When readDataChunk() calls this method, the raw bytes are in 
    * rawReadBuffer, and the final characters will appear in 
    * readBuffer.
    * @param count The number of bytes to convert.
    * @param shift1 The number of bits to shift byte 1.
    * @param shift2 The number of bits to shift byte 2
    * @see #readDataChunk
    * @see #rawReadBuffer
    * @see #readBuffer
    */
  void copyUcs2ReadBuffer (int count, int shift1, int shift2)
    throws java.lang.Exception
  {
    int j = readBufferPos;

    if (count > 0 && (count % 2) != 0) {
      encodingError("odd number of bytes in UCS-2 encoding", -1, count);
    }
    for (int i = 0; i < count; i+=2) {
      readBuffer[j++] =
	(char)(((rawReadBuffer[i] & 0xff) << shift1) |
	       ((rawReadBuffer[i+1] & 0xff) << shift2));
      if (readBuffer[j-1] == '\r') {
	sawCR = true;
      }
    }
    readBufferLength = j;
  }


  /**
    * Convert a buffer of UCS-4-encoded bytes into UTF-16 characters.
    * <p>When readDataChunk() calls this method, the raw bytes are in 
    * rawReadBuffer, and the final characters will appear in 
    * readBuffer.
    * <p>Java has 16-bit chars, but this routine will attempt to use
    * surrogates to encoding values between 0x00010000 and 0x000fffff.
    * @param count The number of bytes to convert.
    * @param shift1 The number of bits to shift byte 1.
    * @param shift2 The number of bits to shift byte 2
    * @param shift3 The number of bits to shift byte 2
    * @param shift4 The number of bits to shift byte 2
    * @see #readDataChunk
    * @see #rawReadBuffer
    * @see #readBuffer
    */
  void copyUcs4ReadBuffer (int count, int shift1, int shift2,
			   int shift3, int shift4)
    throws java.lang.Exception
  {
    int j = readBufferPos;
    int value;

    if (count > 0 && (count % 4) != 0) {
      encodingError("number of bytes in UCS-4 encoding not divisible by 4",
		    -1, count);
    }
    for (int i = 0; i < count; i+=4) {
      value = (((rawReadBuffer[i] & 0xff) << shift1) |
	       ((rawReadBuffer[i+1] & 0xff) << shift2) |
	       ((rawReadBuffer[i+2] & 0xff) << shift3) |
	       ((rawReadBuffer[i+3] & 0xff) << shift4));
      if (value < 0x0000ffff) {
	readBuffer[j++] = (char)value;
	if (value == (int)'\r') {
	  sawCR = true;
	}
      } else if (value < 0x000fffff) {
	readBuffer[j++] = (char)(0xd8 | ((value & 0x000ffc00) >> 10));
	readBuffer[j++] = (char)(0xdc | (value & 0x0003ff));
      } else {
	encodingError("value cannot be represented in UTF-16",
		      value, i);
      }
    }
    readBufferLength = j;
  }


  /**
    * Report a character encoding error.
    */
  void encodingError (String message, int value, int offset)
    throws java.lang.Exception
  {
    String uri;

    if (value >= 0) {
      message = message + " (byte value: 0x" +
	Integer.toHexString(value) + ')';
    }
    if (externalEntity != null) {
      uri = externalEntity.getURL().toString();
    } else {
      uri = baseURI;
    }
    handler.error(message, uri, -1, offset + currentByteCount);
  }



  //////////////////////////////////////////////////////////////////////
  // Local Variables.
  //////////////////////////////////////////////////////////////////////

  /**
    * Re-initialize the variables for each parse.
    */
  void initializeVariables ()
  {
				// No errors; first line
    errorCount = 0;
    line = 1;
    column = 0;

				// Set up the buffers for data and names
    dataBufferPos = 0;
    dataBuffer = new char[DATA_BUFFER_INITIAL];
    nameBufferPos = 0;
    nameBuffer = new char[NAME_BUFFER_INITIAL];

				// Set up the DTD hash tables
    elementInfo = new Hashtable();
    entityInfo = new Hashtable();
    notationInfo = new Hashtable();

				// Set up the variables for the current
				// element context.
    currentElement = null;
    currentElementContent = CONTENT_UNDECLARED;

				// Set up the input variables
    sourceType = INPUT_NONE;
    inputStack = new Stack();
    entityStack = new Stack();
    externalEntity = null;
    tagAttributePos = 0;
    tagAttributes = new String[100];
    rawReadBuffer = new byte[READ_BUFFER_MAX];
    readBufferOverflow = -1;

    context = CONTEXT_NONE;

    symbolTable = new Object[SYMBOL_TABLE_LENGTH];
  }


  /**
    * Clean up after the parse to allow some garbage collection.
    * Leave around anything that might be useful for queries.
    */
  void cleanupVariables ()
  {
    errorCount = -1;
    line = -1;
    column = -1;
    dataBuffer = null;
    nameBuffer = null;
    currentElement = null;
    currentElementContent = CONTENT_UNDECLARED;
    sourceType = INPUT_NONE;
    inputStack = null;
    externalEntity = null;
    entityStack = null;
  }

  //
  // The current XML handler interface.
  //
  XmlHandler handler;

  //
  // I/O information.
  //
  private Reader reader;	// current reader
  private InputStream is;	// current input stream
  private int line;		// current line number
  private int column;		// current column number
  private int sourceType;	// type of input source
  private Stack inputStack;	// stack of input soruces
  private URLConnection externalEntity;	// current external entity
  private int encoding;		// current character encoding.
  private int currentByteCount;	// how many bytes read from current source.

  //
  // Maintain a count of errors.
  //
  private int errorCount;

  //
  // Buffers for decoded but unparsed character input.
  //
  private final static int READ_BUFFER_MAX = 16384;
  private char readBuffer[];
  private int readBufferPos;
  private int readBufferLength;
  private int readBufferOverflow; // overflow character from last data chunk.


  //
  // Buffer for undecoded raw byte input.
  //
  private byte rawReadBuffer[];


  //
  // Buffer for parsed character data.
  //
  private static int DATA_BUFFER_INITIAL = 4096;
  private char dataBuffer[];
  private int dataBufferPos;

  //
  // Buffer for parsed names.
  //
  private static int NAME_BUFFER_INITIAL = 1024;
  private char nameBuffer[];
  private int nameBufferPos;


  //
  // Hashtables for DTD information on elements, entities, and notations.
  //
  private Hashtable elementInfo;
  private Hashtable entityInfo;
  private Hashtable notationInfo;


  //
  // Element type currently in force.
  //
  private String currentElement;
  private int currentElementContent;

  //
  // Base external identifiers for resolution.
  //
  private String basePublicId;
  private String baseURI;
  private int baseEncoding;
  private Reader baseReader;
  private InputStream baseInputStream;
  private char baseInputBuffer[];
  private int baseInputBufferStart;
  private int baseInputBufferLength;

  //
  // Stack of entity names, to help detect recursion.
  //
  private Stack entityStack;

  //
  // Are we in a context where PEs are allowed?
  //
  private int context;

  //
  // Symbol table, for internalising names.
  //
  private Object symbolTable[];
  private final static int SYMBOL_TABLE_LENGTH = 1087;

  //
  // Hash table of attributes found in current start tag.
  //
  private String tagAttributes[];
  private int tagAttributePos;

  //
  // Utility flag: have we noticed a CR while reading the last
  // data chunk?  If so, we will have to go back and normalise
  // CR/LF.
  //
  private boolean sawCR;
}