babbel_xml 0.2.0

Full-featured XML parser, validator, stringifier, and XPath 1.0 engine in pure Rust
Documentation
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
//! # XML Parser Engine
//!
//! Recursive descent XML parser turning character streams ([`XmlSource`]) into DOM trees ([`Document`]).

use crate::alloc_prelude::*;
use crate::document::Document;
use crate::entity::EntityMapper;
use crate::error::{Result, XmlError};
use crate::io::{is_valid_xml_char, is_xml_name_char, is_xml_name_start, XmlSource};
use crate::namespace::{NamespaceScope, QName};
use crate::node::{Attribute, NodeId, NodeKind};
use crate::options::ParseOptions;

/// Main recursive descent XML parser implementation.
#[derive(Debug)]
pub struct XmlParser<'a> {
    source: XmlSource,
    options: ParseOptions,
    entity_mapper: EntityMapper,
    namespace_scope: NamespaceScope,
    element_count: usize,
    total_attribute_count: usize,
    standalone: Option<bool>,
    external_entities: Vec<String>,
    unparsed_entities: Vec<String>,
    _phantom: core::marker::PhantomData<&'a ()>,
}

impl<'a> XmlParser<'a> {
    /// Instantiates a new [`XmlParser`] with an input source and parse options.
    pub fn new(source: XmlSource, options: ParseOptions) -> Self {
        let mapper = EntityMapper::with_limits(
            options.max_entity_expansion_depth,
            options.max_total_entity_expansion_size,
        );
        Self {
            source,
            options,
            entity_mapper: mapper,
            namespace_scope: NamespaceScope::new(),
            element_count: 0,
            total_attribute_count: 0,
            standalone: None,
            external_entities: Vec::new(),
            unparsed_entities: Vec::new(),
            _phantom: core::marker::PhantomData,
        }
    }

    /// Parses the entire input source into a DOM [`Document`].
    pub fn parse(&mut self) -> Result<Document> {
        self.options.check_xml_size(self.source.len())?;
        let mut doc = Document::new();

        // XML 1.0 §2.8 [22]: XML declaration must appear at the very start of document if present.
        // No whitespace or comments can precede it.
        if self.source.starts_with("<?xml") {
            self.parse_declaration(&mut doc)?;
        }

        self.parse_prolog(&mut doc)?;

        let root_container_id = doc.root_id().unwrap_or(0);
        self.parse_element(&mut doc, root_container_id, 0)?;

        self.parse_epilog(&mut doc)?;

        self.source.skip_whitespace();
        if !self.source.is_eof() {
            if self.source.starts_with("<") {
                return Err(XmlError::SyntaxError {
                    message: "Multiple root elements forbidden in well-formed XML".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            } else {
                return Err(XmlError::SyntaxError {
                    message: "Unexpected trailing content after root element".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
        }
        Ok(doc)
    }

    /// Parses XML declaration (`<?xml version="..." encoding="..."?>`).
    fn parse_declaration(&mut self, doc: &mut Document) -> Result<()> {
        self.source.consume("<?xml");
        // XML 1.0 §2.8 [23]: XMLDecl ::= '<?xml' VersionInfo ... where VersionInfo begins with S
        let ws = self.source.skip_whitespace();
        if ws == 0 {
            return Err(XmlError::SyntaxError {
                message: "Expected whitespace after '<?xml'".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }

        // First attribute MUST be version
        let (k1, v1) = self.parse_attribute()?;
        if k1 != "version" {
            return Err(XmlError::SyntaxError {
                message: format!("XML declaration must begin with 'version', found '{k1}'"),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        // XML 1.0 §2.8 [26]: VersionNum ::= '1.' [0-9]+
        if !v1.starts_with("1.") || v1.len() < 3 || !v1[2..].chars().all(|c| c.is_ascii_digit()) {
            return Err(XmlError::SyntaxError {
                message: format!("Invalid XML version format '{v1}'"),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        let version = v1;
        let mut encoding = None;
        let mut standalone = None;

        while !self.source.is_eof() && !self.source.starts_with("?>") {
            let ws_attr = self.source.skip_whitespace();
            if self.source.starts_with("?>") {
                break;
            }
            if ws_attr == 0 {
                return Err(XmlError::SyntaxError {
                    message: "Whitespace required before attribute in XML declaration".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }

            let (key, val) = self.parse_attribute()?;
            match key.as_str() {
                "encoding" => {
                    if standalone.is_some() {
                        return Err(XmlError::SyntaxError {
                            message: "'encoding' declaration must precede 'standalone' in XML declaration".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                    if encoding.is_some() {
                        return Err(XmlError::SyntaxError {
                            message: "Duplicate 'encoding' in XML declaration".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                    // Validate EncName: [A-Za-z] ([A-Za-z0-9._] | '-')*
                    let mut chars = val.chars();
                    let valid = match chars.next() {
                        Some(f) => f.is_ascii_alphabetic() && chars.all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-'),
                        None => false,
                    };
                    if !valid {
                        return Err(XmlError::SyntaxError {
                            message: format!("Invalid encoding name '{val}'"),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                    encoding = Some(val);
                }
                "standalone" => {
                    if standalone.is_some() {
                        return Err(XmlError::SyntaxError {
                            message: "Duplicate 'standalone' in XML declaration".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                    // XML 1.0 §2.9 [32]: standalone value must be strictly "yes" or "no" (lowercase)
                    if val != "yes" && val != "no" {
                        return Err(XmlError::SyntaxError {
                            message: format!("Invalid standalone value '{val}', must be 'yes' or 'no'"),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                    standalone = Some(val == "yes");
                }
                other => {
                    return Err(XmlError::SyntaxError {
                        message: format!("Unexpected attribute '{other}' in XML declaration"),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
            }
        }

        self.source.skip_whitespace();
        if !self.source.consume("?>") {
            return Err(XmlError::SyntaxError {
                message: "Unclosed XML declaration".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }

        // XML 1.0 §4.3.3: Fatal error if declared encoding conflicts with actual stream encoding
        if let Some(enc) = &encoding {
            if (enc.eq_ignore_ascii_case("UTF-16")
                || enc.eq_ignore_ascii_case("UTF-16LE")
                || enc.eq_ignore_ascii_case("UTF-16BE"))
                && !self.options.is_utf16
            {
                return Err(XmlError::SyntaxError {
                    message: format!("Declared encoding '{enc}' does not match byte stream encoding"),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
        }

        self.standalone = standalone;
        let decl_id = doc.add_node(NodeKind::Declaration(Box::new(crate::node::DeclarationData {
            version: version.into_boxed_str(),
            encoding: encoding.map(String::into_boxed_str),
            standalone,
        })));
        doc.set_declaration_id(decl_id);

        let prolog_id = doc.prolog_id().unwrap_or(0);
        doc.append_child(prolog_id, decl_id)?;

        Ok(())
    }

    /// Parses prolog items (comments, PIs, DOCTYPE) prior to the root element tag.
    fn parse_prolog(&mut self, doc: &mut Document) -> Result<()> {
        let prolog_id = doc.prolog_id().unwrap_or(0);

        loop {
            self.source.skip_whitespace();
            if self.source.starts_with("<!--") {
                let comment_id = self.parse_comment(doc)?;
                doc.append_child(prolog_id, comment_id)?;
            } else if self.source.starts_with("<?") {
                let pi_id = self.parse_pi(doc)?;
                doc.append_child(prolog_id, pi_id)?;
            } else if self.source.starts_with("<!DOCTYPE") {
                let dtd_id = self.parse_doctype(doc)?;
                doc.set_dtd_id(dtd_id);
                doc.append_child(prolog_id, dtd_id)?;
            } else {
                break;
            }
        }
        Ok(())
    }

    /// Parses epilog items (comments, PIs) following the root element tag.
    fn parse_epilog(&mut self, doc: &mut Document) -> Result<()> {
        let root_container_id = doc.root_id().unwrap_or(0);
        loop {
            self.source.skip_whitespace();
            if self.source.starts_with("<!--") {
                let comment_id = self.parse_comment(doc)?;
                doc.append_child(root_container_id, comment_id)?;
            } else if self.source.starts_with("<?") {
                let pi_id = self.parse_pi(doc)?;
                doc.append_child(root_container_id, pi_id)?;
            } else {
                break;
            }
        }
        Ok(())
    }

    /// Parses a single XML element tag, its attributes, and child content recursively.
    fn parse_element(&mut self, doc: &mut Document, parent_id: NodeId, depth: usize) -> Result<()> {
        self.namespace_scope.push_scope();
        let res = self.parse_element_internal(doc, parent_id, depth);
        self.namespace_scope.pop_scope();
        res
    }

    fn parse_element_internal(&mut self, doc: &mut Document, parent_id: NodeId, depth: usize) -> Result<()> {
        self.options.check_nesting_depth(depth)?;

        self.element_count += 1;
        self.options.check_element_count(self.element_count)?;

        if !self.source.consume("<") {
            return Err(XmlError::SyntaxError {
                message: "Expected '<' at start of element".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }

        let name = self.parse_name()?;
        if name.is_empty() {
            return Err(XmlError::SyntaxError {
                message: "Empty element tag name".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }

        // Namespaces in XML 1.0 §3: Elements must not have the prefix 'xmlns'
        if name.starts_with("xmlns:") {
            return Err(XmlError::SyntaxError {
                message: format!("Element <{name}> must not have prefix 'xmlns'"),
                line: self.source.line(),
                col: self.source.col(),
            });
        }

        self.source.skip_whitespace();
        let mut attributes = Vec::new();

        while !self.source.is_eof() && !self.source.starts_with(">") && !self.source.starts_with("/>") {
            let (attr_name, attr_value) = self.parse_attribute()?;
            
            // Check duplicate attribute error
            if attributes.iter().any(|a: &Attribute| *a.name == attr_name) {
                return Err(XmlError::SyntaxError {
                    message: format!("Duplicate attribute '{attr_name}' on element <{name}>"),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }

            // Register namespaces declared on this element
            if self.options.namespace_aware {
                if attr_name == "xmlns" {
                    self.namespace_scope.declare(None, attr_value.trim());
                } else if let Some(prefix) = attr_name.strip_prefix("xmlns:") {
                    self.namespace_scope.declare(Some(prefix), attr_value.trim());
                }
            }

            attributes.push(Attribute::new(attr_name, attr_value));

            self.total_attribute_count += 1;
            self.options.check_attribute_count(attributes.len())?;
            self.options.check_total_attribute_count(self.total_attribute_count)?;

            let ws = self.source.skip_whitespace();
            if self.source.starts_with(">") || self.source.starts_with("/>") {
                break;
            }
            if ws == 0 {
                return Err(XmlError::SyntaxError {
                    message: "Whitespace required between attributes in element tag".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
        }

        // Validate namespace prefixes and collisions
        if self.options.namespace_aware {
            // Check element prefix
            let (elem_pfx, _) = QName::split_prefix(&name);
            if let Some(pfx) = elem_pfx {
                if self.namespace_scope.resolve_prefix(Some(pfx)).is_none() {
                    return Err(XmlError::SyntaxError {
                        message: format!("Undeclared element namespace prefix '{pfx}'"),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
            }

            // Check attribute prefixes and attribute namespace collisions
            let mut resolved_attrs: Vec<(Option<String>, String)> = Vec::new();
            for attr in &attributes {
                let (attr_pfx, local) = QName::split_prefix(&attr.name);
                let uri_opt = if let Some(pfx) = attr_pfx {
                    if pfx == "xmlns" {
                        None
                    } else {
                        match self.namespace_scope.resolve_prefix(Some(pfx)) {
                            Some(u) => Some(u.to_string()),
                            None => {
                                return Err(XmlError::SyntaxError {
                                    message: format!("Undeclared attribute namespace prefix '{pfx}'"),
                                    line: self.source.line(),
                                    col: self.source.col(),
                                });
                            }
                        }
                    }
                } else {
                    None
                };

                if let Some(uri) = &uri_opt {
                    if resolved_attrs.iter().any(|(u, l)| u.as_deref() == Some(uri.as_str()) && l == local) {
                        return Err(XmlError::SyntaxError {
                            message: format!("Attribute collision: multiple attributes with namespace '{uri}' and local name '{local}'"),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                }
                resolved_attrs.push((uri_opt, local.to_string()));
            }
        }

        let elem_id = doc.add_node(NodeKind::Element {
            name: name.clone().into_boxed_str(),
            attributes,
        });
        doc.append_child(parent_id, elem_id)?;

        if self.source.consume("/>") {
            return Ok(());
        }

        if !self.source.consume(">") {
            return Err(XmlError::SyntaxError {
                message: format!("Expected '>' or '/>' for element <{name}>"),
                line: self.source.line(),
                col: self.source.col(),
            });
        }

        // Parse element body / child content
        loop {
            if self.source.is_eof() {
                return Err(XmlError::SyntaxError {
                    message: format!("Unclosed element <{name}>"),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }

            if self.source.starts_with("</") {
                self.source.consume("</");
                let end_name = self.parse_name()?;
                self.source.skip_whitespace();

                if end_name != name {
                    return Err(XmlError::SyntaxError {
                        message: format!("Mismatched closing tag: expected </{name}>, found </{end_name}>"),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }

                if !self.source.consume(">") {
                    return Err(XmlError::SyntaxError {
                        message: format!("Expected '>' after closing tag </{name}>"),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }

                break;
            } else if self.source.starts_with("<![CDATA[") {
                let cdata_id = self.parse_cdata(doc)?;
                doc.append_child(elem_id, cdata_id)?;
            } else if self.source.starts_with("<!--") {
                let comment_id = self.parse_comment(doc)?;
                doc.append_child(elem_id, comment_id)?;
            } else if self.source.starts_with("<?") {
                let pi_id = self.parse_pi(doc)?;
                doc.append_child(elem_id, pi_id)?;
            } else if self.source.starts_with("<") {
                self.parse_element(doc, elem_id, depth + 1)?;
            } else {
                let text_id = self.parse_text(doc)?;
                if let Some(t_node) = doc.get_node(text_id) {
                    if let NodeKind::Text(t) = &t_node.kind {
                        if !t.is_empty() {
                            doc.append_child(elem_id, text_id)?;
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Parses attribute key-value pair (`key="value"`).
    fn parse_attribute(&mut self) -> Result<(String, String)> {
        let key = self.parse_name()?;
        if key.is_empty() {
            return Err(XmlError::SyntaxError {
                message: "Attribute name cannot be empty".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        self.source.skip_whitespace();

        if !self.source.consume("=") {
            return Err(XmlError::SyntaxError {
                message: format!("Expected '=' after attribute '{key}'"),
                line: self.source.line(),
                col: self.source.col(),
            });
        }

        self.source.skip_whitespace();
        let quote = self.source.next_char().ok_or_else(|| XmlError::SyntaxError {
            message: format!("Expected quote after '=' for attribute '{key}'"),
            line: self.source.line(),
            col: self.source.col(),
        })?;

        if quote != '"' && quote != '\'' {
            return Err(XmlError::SyntaxError {
                message: format!("Invalid attribute quote character '{quote}'"),
                line: self.source.line(),
                col: self.source.col(),
            });
        }

        let mut raw_val = String::new();
        while let Some(ch) = self.source.next_char() {
            if ch == '<' {
                return Err(XmlError::SyntaxError {
                    message: format!("Unescaped '<' is forbidden in attribute value for '{key}'"),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            if !is_valid_xml_char(ch) {
                return Err(XmlError::SyntaxError {
                    message: format!("Forbidden XML character '\\u{{{:x}}}' in attribute value", ch as u32),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            if ch == quote {
                self.check_attribute_entities(&raw_val)?;
                let expanded_val = self.entity_mapper.expand(&raw_val)?;

                // Namespaces in XML 1.0 validation checks
                if key == "xmlns" {
                    if expanded_val == "http://www.w3.org/XML/1998/namespace" {
                        return Err(XmlError::SyntaxError {
                            message: "The xml namespace must not be declared as the default namespace".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                    if expanded_val == "http://www.w3.org/2000/xmlns/" {
                        return Err(XmlError::SyntaxError {
                            message: "The xmlns namespace must not be declared as a namespace".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                } else if key == "xmlns:xml" {
                    if expanded_val != "http://www.w3.org/XML/1998/namespace" {
                        return Err(XmlError::SyntaxError {
                            message: "The prefix 'xml' can only be bound to 'http://www.w3.org/XML/1998/namespace'".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                } else if key == "xmlns:xmlns" {
                    return Err(XmlError::SyntaxError {
                        message: "The prefix 'xmlns' must not be declared".into(),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                } else if key.starts_with("xmlns:") {
                    if expanded_val == "http://www.w3.org/XML/1998/namespace" {
                        return Err(XmlError::SyntaxError {
                            message: "The xml namespace must not be bound to any other prefix".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                    if expanded_val == "http://www.w3.org/2000/xmlns/" {
                        return Err(XmlError::SyntaxError {
                            message: "Prefix cannot be bound to the xmlns namespace".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                    if expanded_val.is_empty() {
                        return Err(XmlError::SyntaxError {
                            message: "Empty namespace URI is illegal for prefixed namespace in XML 1.0".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                }

                return Ok((key, expanded_val));
            }
            raw_val.push(ch);
        }

        Err(XmlError::SyntaxError {
            message: format!("Unterminated value for attribute '{key}'"),
            line: self.source.line(),
            col: self.source.col(),
        })
    }

    /// Parses text content up to the next `<` tag start.
    fn parse_text(&mut self, doc: &mut Document) -> Result<NodeId> {
        let mut raw_text = String::new();
        while let Some(ch) = self.source.peek() {
            if ch == '<' {
                break;
            }
            if !is_valid_xml_char(ch) {
                return Err(XmlError::SyntaxError {
                    message: format!("Forbidden XML character '\\u{{{:x}}}'", ch as u32),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            let ch = self.source.next_char().ok_or_else(|| XmlError::SyntaxError {
                message: "Unexpected EOF while reading text".into(),
                line: self.source.line(),
                col: self.source.col(),
            })?;
            raw_text.push(ch);
            self.options.check_text_node_size(raw_text.len())?;
        }

        if raw_text.contains("]]>") {
            return Err(XmlError::SyntaxError {
                message: "The sequence ']]>' is forbidden in character data".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }

        let mut pos = 0;
        let bytes = raw_text.as_bytes();
        while pos < bytes.len() {
            if bytes[pos] == b'&' {
                if let Some(semi_offset) = raw_text[pos..].find(';') {
                    let semi_idx = pos + semi_offset;
                    let ref_name = &raw_text[pos + 1..semi_idx];
                    if !ref_name.starts_with('#') {
                        if self.unparsed_entities.iter().any(|u| u == ref_name) {
                            return Err(XmlError::SyntaxError {
                                message: format!("Unparsed entity '{ref_name}' cannot be referenced in content (WFC: Parsed Entity)"),
                                line: self.source.line(),
                                col: self.source.col(),
                            });
                        }
                        if ref_name != "lt" && ref_name != "gt" && ref_name != "amp" && ref_name != "quot" && ref_name != "apos" {
                            if !self.external_entities.iter().any(|e| e == ref_name) {
                                if let Some(val) = self.entity_mapper.get(ref_name) {
                                    self.validate_entity_replacement_text(ref_name, val)?;
                                }
                            }
                        }
                    }
                    pos = semi_idx + 1;
                } else {
                    pos += 1;
                }
            } else {
                pos += 1;
            }
        }

        let expanded = self.entity_mapper.expand(&raw_text)?;
        Ok(doc.add_node(NodeKind::Text(expanded.into_boxed_str())))
    }

    /// Parses CDATA section (`<![CDATA[...]]>`).
    fn parse_cdata(&mut self, doc: &mut Document) -> Result<NodeId> {
        self.source.consume("<![CDATA[");
        let mut content = String::new();

        while !self.source.is_eof() {
            if self.source.starts_with("]]>") {
                self.source.consume("]]>");
                return Ok(doc.add_node(NodeKind::CData(content.into_boxed_str())));
            }
            let ch = self.source.next_char().ok_or_else(|| XmlError::SyntaxError {
                message: "Unterminated CDATA section".into(),
                line: self.source.line(),
                col: self.source.col(),
            })?;
            if !is_valid_xml_char(ch) {
                return Err(XmlError::SyntaxError {
                    message: format!("Forbidden XML character '\\u{{{:x}}}' in CDATA", ch as u32),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            content.push(ch);
            self.options.check_text_node_size(content.len())?;
        }

        Err(XmlError::SyntaxError {
            message: "Unterminated CDATA section".into(),
            line: self.source.line(),
            col: self.source.col(),
        })
    }

    /// Parses XML comment (`<!-- ... -->`).
    fn parse_comment(&mut self, doc: &mut Document) -> Result<NodeId> {
        self.source.consume("<!--");
        let mut comment = String::new();

        while !self.source.is_eof() {
            if self.source.starts_with("-->") {
                if comment.ends_with('-') {
                    return Err(XmlError::SyntaxError {
                        message: "Comment must not end in '--->'".into(),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
                self.source.consume("-->");
                return Ok(doc.add_node(NodeKind::Comment(comment.into_boxed_str())));
            }
            let ch = self.source.next_char().ok_or_else(|| XmlError::SyntaxError {
                message: "Unterminated XML comment".into(),
                line: self.source.line(),
                col: self.source.col(),
            })?;
            if !is_valid_xml_char(ch) {
                return Err(XmlError::SyntaxError {
                    message: format!("Forbidden XML character '\\u{{{:x}}}' in comment", ch as u32),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            if comment.ends_with('-') && ch == '-' {
                return Err(XmlError::SyntaxError {
                    message: "The string '--' is forbidden inside comments".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            comment.push(ch);
        }

        Err(XmlError::SyntaxError {
            message: "Unterminated XML comment".into(),
            line: self.source.line(),
            col: self.source.col(),
        })
    }

    /// Parses processing instruction (`<?target data?>`).
    fn parse_pi(&mut self, doc: &mut Document) -> Result<NodeId> {
        self.source.consume("<?");
        let target = self.parse_name()?;
        if target.is_empty() {
            return Err(XmlError::SyntaxError {
                message: "Processing instruction target cannot be empty".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        if target.eq_ignore_ascii_case("xml") {
            return Err(XmlError::SyntaxError {
                message: "Processing instruction target cannot be 'xml'".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        if self.options.namespace_aware && target.contains(':') {
            return Err(XmlError::SyntaxError {
                message: format!("Processing instruction target '{target}' cannot contain a colon"),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        if self.source.starts_with("?>") {
            self.source.consume("?>");
            return Ok(doc.add_node(NodeKind::ProcessingInstruction {
                target: target.into_boxed_str(),
                data: "".into(),
            }));
        }

        if self.source.skip_whitespace() == 0 {
            return Err(XmlError::SyntaxError {
                message: "Whitespace required between processing instruction target and data".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }

        let mut data = String::new();
        while !self.source.is_eof() {
            if self.source.starts_with("?>") {
                self.source.consume("?>");
                return Ok(doc.add_node(NodeKind::ProcessingInstruction {
                    target: target.into_boxed_str(),
                    data: data.into_boxed_str(),
                }));
            }
            let ch = self.source.next_char().ok_or_else(|| XmlError::SyntaxError {
                message: "Unterminated processing instruction".into(),
                line: self.source.line(),
                col: self.source.col(),
            })?;
            if !is_valid_xml_char(ch) {
                return Err(XmlError::SyntaxError {
                    message: format!("Forbidden XML character '\\u{{{:x}}}' in processing instruction", ch as u32),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            data.push(ch);
        }

        Err(XmlError::SyntaxError {
            message: "Unterminated processing instruction".into(),
            line: self.source.line(),
            col: self.source.col(),
        })
    }

    /// Parses DTD DOCTYPE definition (`<!DOCTYPE name ...>`).
    fn parse_doctype(&mut self, doc: &mut Document) -> Result<NodeId> {
        self.source.consume("<!DOCTYPE");
        self.source.skip_whitespace();

        let name = self.parse_name()?;
        self.source.skip_whitespace();

        let mut public_id = None;
        let mut system_id = None;
        let mut internal_subset = None;

        if self.source.consume("PUBLIC") {
            if self.source.skip_whitespace() == 0 {
                return Err(XmlError::SyntaxError {
                    message: "Whitespace required after 'PUBLIC'".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            public_id = Some(self.parse_pubid_literal()?);
            if self.source.skip_whitespace() == 0 {
                return Err(XmlError::SyntaxError {
                    message: "Whitespace required between Public ID and System ID".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            system_id = Some(self.parse_quoted_string()?);
        } else if self.source.consume("SYSTEM") {
            if self.source.skip_whitespace() == 0 {
                return Err(XmlError::SyntaxError {
                    message: "Whitespace required after 'SYSTEM'".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            system_id = Some(self.parse_quoted_string()?);
        }

        self.source.skip_whitespace();
        if self.source.consume("[") {
            let subset = self.parse_internal_subset()?;
            internal_subset = Some(subset);
        }

        self.source.skip_whitespace();
        if !self.source.consume(">") {
            return Err(XmlError::SyntaxError {
                message: "Unclosed DOCTYPE declaration".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }

        // Register external DTD entity declarations if allowed
        #[cfg(feature = "std")]
        if let Some(sys_id) = &system_id {
            if self.options.allow_external_entities {
                let dtd_path = if let Some(base) = &self.options.base_dir {
                    std::path::Path::new(base).join(sys_id.as_str())
                } else {
                    std::path::PathBuf::from(sys_id.as_str())
                };
                if let Ok(content) = std::fs::read_to_string(&dtd_path) {
                    let _ = self.register_entities_from_text(&content);
                }
            }
        }

        // Register entity declarations from internal subset
        if let Some(subset) = &internal_subset {
            self.register_entities_from_text(subset)?;
        }

        // XML 1.0 §4.1: If DOCTYPE contains parameter entities or external subsets,
        // undeclared entity references are validity errors, not well-formedness errors.
        // In a standalone document or one without external subset or parameter entities,
        // undeclared entity references are strictly well-formedness errors.
        let is_standalone = self.standalone == Some(true);
        if !is_standalone
            && (system_id.is_some()
                || public_id.is_some()
                || internal_subset.as_ref().map(|s| s.contains('%')).unwrap_or(false))
        {
            self.entity_mapper.allow_undeclared = true;
        }

        Ok(doc.add_node(NodeKind::DocTypeDefinition(Box::new(crate::node::DocTypeData {
            name: name.into_boxed_str(),
            public_id: public_id.map(String::into_boxed_str),
            system_id: system_id.map(String::into_boxed_str),
            internal_subset: internal_subset.map(String::into_boxed_str),
        }))))
    }

    /// Helper registering entity declarations from a DTD text subset.
    fn register_entities_from_text(&mut self, text: &str) -> Result<()> {
        let mut external_entities: Vec<String> = Vec::new();

        for line in text.lines() {
            let trimmed = line.trim();
            if trimmed.starts_with("<!ENTITY") {
                let parts: Vec<&str> = trimmed.split_whitespace().collect();
                if parts.len() >= 3 {
                    let is_param = parts[1] == "%";
                    let (name_idx, val_idx) = if is_param && parts.len() >= 4 {
                        (2, 3)
                    } else {
                        (1, 2)
                    };
                    let ent_name = parts[name_idx];
                    if self.options.namespace_aware && ent_name.contains(':') {
                        return Err(XmlError::SyntaxError {
                            message: format!("Entity name '{ent_name}' cannot contain a colon in namespace-aware XML"),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                    let is_external = trimmed.contains("SYSTEM") || trimmed.contains("PUBLIC");
                    if is_external {
                        external_entities.push(ent_name.to_string());
                        self.external_entities.push(ent_name.to_string());
                    }
                    if trimmed.contains("NDATA") {
                        self.unparsed_entities.push(ent_name.to_string());
                    }
                    if is_external && !self.options.allow_external_entities {
                        return Err(XmlError::SecurityLimitExceeded(
                            "External entity references in DOCTYPE are forbidden by security policy".into(),
                        ));
                    }
                    if is_external && self.options.allow_external_entities && trimmed.contains("SYSTEM") && !trimmed.contains("NDATA") {
                        let raw_val = parts[val_idx..].join(" ");
                        let sys_val = raw_val.trim_matches(|c| c == '"' || c == '\'' || c == '>' || c == ';').trim();
                        let file_name = sys_val.strip_prefix("SYSTEM").unwrap_or(sys_val).trim().trim_matches(|c| c == '"' || c == '\'');
                        #[cfg(feature = "std")]
                        {
                            let file_path = if let Some(base) = &self.options.base_dir {
                                std::path::Path::new(base).join(file_name)
                            } else {
                                std::path::PathBuf::from(file_name)
                            };
                            if let Ok(bytes) = std::fs::read(&file_path) {
                                if let Ok((loaded_text, _)) = babbel_core::encoding::detect_encoding_and_strip_bom(&bytes) {
                                    // XML 1.0 §4.3.4: An XML 1.0 document cannot include external entity with version 1.1
                                    if loaded_text.contains("<?xml") && (loaded_text.contains("version=\"1.1\"") || loaded_text.contains("version='1.1'")) {
                                        return Err(XmlError::SyntaxError {
                                            message: "XML 1.0 document cannot include external entity with version 1.1".into(),
                                            line: self.source.line(),
                                            col: self.source.col(),
                                        });
                                    }
                                    if is_param {
                                        let _ = self.register_entities_from_text(&loaded_text);
                                    }
                                    self.entity_mapper.register(ent_name, &*loaded_text);
                                    continue;
                                }
                            }
                        }
                    }
                    let raw_val = parts[val_idx..].join(" ");
                    let val = raw_val.trim_matches(|c| c == '"' || c == '\'' || c == '>');
                    self.entity_mapper.register(ent_name, val);
                }
            } else if trimmed.starts_with("<!NOTATION") {
                let parts: Vec<&str> = trimmed.split_whitespace().collect();
                if parts.len() >= 2 {
                    let not_name = parts[1];
                    if self.options.namespace_aware && not_name.contains(':') {
                        return Err(XmlError::SyntaxError {
                            message: format!("Notation name '{not_name}' cannot contain a colon in namespace-aware XML"),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                }
            } else if trimmed.starts_with("<!ATTLIST") {
                // W3C XML 1.0 §3.1: Attribute values must not contain references to external entities
                for ext in &external_entities {
                    let needle = format!("&{ext};");
                    if trimmed.contains(&needle) {
                        return Err(XmlError::SyntaxError {
                            message: format!("Attribute values must not contain references to external entity '&{ext};'"),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                }
            }
        }
        Ok(())
    }

    fn check_qname(&self, name: &str) -> Result<()> {
        if !self.options.namespace_aware {
            return Ok(());
        }
        let colons = name.matches(':').count();
        if colons > 1 {
            return Err(XmlError::SyntaxError {
                message: format!("QName '{name}' cannot contain multiple colons"),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        if name.starts_with(':') || name.ends_with(':') {
            return Err(XmlError::SyntaxError {
                message: format!("QName '{name}' cannot start or end with a colon"),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        Ok(())
    }

    /// Helper parsing an identifier / tag name string.
    fn parse_name(&mut self) -> Result<String> {
        let start = self.source.position();
        if let Some(ch) = self.source.peek() {
            if !is_xml_name_start(ch) {
                return Ok(String::new());
            }
            self.source.next_char();
        }
        while let Some(ch) = self.source.peek() {
            if is_xml_name_char(ch) {
                self.source.next_char();
            } else {
                break;
            }
        }
        let end = self.source.position();
        let name = self.source.slice_range(start, end).to_string();
        if !name.is_empty() {
            self.check_qname(&name)?;
        }
        Ok(name)
    }

    /// Helper parsing a single- or double-quoted string.
    fn parse_quoted_string(&mut self) -> Result<String> {
        let quote = self.source.next_char().ok_or_else(|| XmlError::SyntaxError {
            message: "Expected quote for string literal".into(),
            line: self.source.line(),
            col: self.source.col(),
        })?;

        let mut s = String::new();
        while let Some(ch) = self.source.next_char() {
            if ch == quote {
                return Ok(s);
            }
            if !is_valid_xml_char(ch) {
                return Err(XmlError::SyntaxError {
                    message: format!("Forbidden XML character '\\u{{{:x}}}' in string literal", ch as u32),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            s.push(ch);
        }

        Err(XmlError::SyntaxError {
            message: "Unterminated string literal".into(),
            line: self.source.line(),
            col: self.source.col(),
        })
    }

    fn is_pubid_char(ch: char) -> bool {
        matches!(ch, ' ' | '\r' | '\n' | 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '\'' | '(' | ')' | '+' | ',' | '.' | '/' | ':' | '=' | '?' | ';' | '!' | '*' | '#' | '@' | '$' | '_' | '%')
    }

    fn parse_pubid_literal(&mut self) -> Result<String> {
        let quote = self.source.next_char().ok_or_else(|| XmlError::SyntaxError {
            message: "Expected quote for PubidLiteral".into(),
            line: self.source.line(),
            col: self.source.col(),
        })?;
        if quote != '"' && quote != '\'' {
            return Err(XmlError::SyntaxError {
                message: "PubidLiteral must start with single or double quote".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        let mut s = String::new();
        while let Some(ch) = self.source.next_char() {
            if ch == quote {
                return Ok(s);
            }
            if !Self::is_pubid_char(ch) || (quote == '\'' && ch == '\'') {
                return Err(XmlError::SyntaxError {
                    message: format!("Illegal character in PubidLiteral: '{}'", ch),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            s.push(ch);
        }
        Err(XmlError::SyntaxError {
            message: "Unterminated PubidLiteral".into(),
            line: self.source.line(),
            col: self.source.col(),
        })
    }

    fn parse_nmtoken(&mut self) -> Result<String> {
        let start = self.source.position();
        while let Some(ch) = self.source.peek() {
            if is_xml_name_char(ch) {
                self.source.next_char();
            } else {
                break;
            }
        }
        let end = self.source.position();
        if start == end {
            return Err(XmlError::SyntaxError {
                message: "Expected Nmtoken".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        Ok(self.source.slice_range(start, end).to_string())
    }

    fn parse_entity_value(&mut self) -> Result<String> {
        let quote = self.source.next_char().ok_or_else(|| XmlError::SyntaxError {
            message: "Expected quote for EntityValue".into(),
            line: self.source.line(),
            col: self.source.col(),
        })?;
        if quote != '"' && quote != '\'' {
            return Err(XmlError::SyntaxError {
                message: "EntityValue must be quoted".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        let mut s = String::new();
        while let Some(ch) = self.source.peek() {
            if ch == quote {
                self.source.next_char();
                return Ok(s);
            }
            if ch == '%' {
                return Err(XmlError::SyntaxError {
                    message: "Parameter-entity references must not occur within markup declarations in the internal DTD subset (WFC: In Subset)".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            } else if ch == '&' {
                self.source.next_char();
                if self.source.consume("#") {
                    let hex = self.source.consume("x");
                    let mut num_str = String::new();
                    while let Some(nc) = self.source.peek() {
                        if (hex && nc.is_ascii_hexdigit()) || (!hex && nc.is_ascii_digit()) {
                            num_str.push(nc);
                            self.source.next_char();
                        } else {
                            break;
                        }
                    }
                    if num_str.is_empty() {
                        return Err(XmlError::SyntaxError {
                            message: "Expected digits in numeric character reference".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                    if !self.source.consume(";") {
                        return Err(XmlError::SyntaxError {
                            message: "Expected ';' terminating numeric character reference".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                    let codepoint = if hex {
                        u32::from_str_radix(&num_str, 16)
                    } else {
                        num_str.parse::<u32>()
                    };
                    match codepoint {
                        Ok(cp) => {
                            if let Some(c) = char::from_u32(cp) {
                                if !is_valid_xml_char(c) {
                                    return Err(XmlError::SyntaxError {
                                        message: format!("Forbidden XML character '\\u{{{:x}}}' in character reference", cp),
                                        line: self.source.line(),
                                        col: self.source.col(),
                                    });
                                }
                                s.push(c);
                            } else {
                                return Err(XmlError::SyntaxError {
                                    message: format!("Invalid code point {cp} in character reference"),
                                    line: self.source.line(),
                                    col: self.source.col(),
                                });
                            }
                        }
                        Err(_) => {
                            return Err(XmlError::SyntaxError {
                                message: "Malformed numeric character reference".into(),
                                line: self.source.line(),
                                col: self.source.col(),
                            });
                        }
                    }
                } else {
                    s.push('&');
                    let name = self.parse_name()?;
                    if name.is_empty() {
                        return Err(XmlError::SyntaxError {
                            message: "Expected Name in entity reference inside EntityValue".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                    s.push_str(&name);
                    if !self.source.consume(";") {
                        return Err(XmlError::SyntaxError {
                            message: "Expected ';' terminating entity reference inside EntityValue".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                    s.push(';');
                }
            } else {
                if !is_valid_xml_char(ch) {
                    return Err(XmlError::SyntaxError {
                        message: format!("Forbidden XML character '\\u{{{:x}}}' in EntityValue", ch as u32),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
                self.source.next_char();
                s.push(ch);
            }
        }
        Err(XmlError::SyntaxError {
            message: "Unterminated EntityValue".into(),
            line: self.source.line(),
            col: self.source.col(),
        })
    }

    fn parse_mixed(&mut self) -> Result<()> {
        let mut count = 0;
        loop {
            self.source.skip_whitespace();
            if self.source.consume("|") {
                count += 1;
                self.source.skip_whitespace();
                let name = self.parse_name()?;
                if name.is_empty() {
                    return Err(XmlError::SyntaxError {
                        message: "Expected element name after '|' in Mixed content".into(),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
            } else {
                break;
            }
        }
        self.source.skip_whitespace();
        if !self.source.consume(")") {
            return Err(XmlError::SyntaxError {
                message: "Expected ')' terminating Mixed content".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        if count > 0 {
            if !self.source.consume("*") {
                return Err(XmlError::SyntaxError {
                    message: "Mixed content with element names must end with ')*'".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
        } else {
            let _ = self.source.consume("*");
        }
        if let Some(ch) = self.source.peek() {
            if ch == '?' || ch == '+' || ch == '*' {
                return Err(XmlError::SyntaxError {
                    message: "Illegal quantifier on Mixed content".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
        }
        Ok(())
    }

    fn parse_cp(&mut self) -> Result<()> {
        self.source.skip_whitespace();
        if self.source.peek() == Some('(') {
            self.parse_children_group()?;
        } else {
            let name = self.parse_name()?;
            if name.is_empty() {
                return Err(XmlError::SyntaxError {
                    message: "Expected element name in content particle".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
        }
        if let Some(ch) = self.source.peek() {
            if ch == '?' || ch == '*' || ch == '+' {
                self.source.next_char();
            }
        }
        Ok(())
    }

    fn parse_children_group(&mut self) -> Result<()> {
        if !self.source.consume("(") {
            return Err(XmlError::SyntaxError {
                message: "Expected '(' starting children group".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        self.source.skip_whitespace();
        if self.source.peek() == Some(')') {
            return Err(XmlError::SyntaxError {
                message: "Empty children group '()' is not allowed".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        self.parse_cp()?;

        let mut sep_choice = false;
        let mut sep_seq = false;

        loop {
            self.source.skip_whitespace();
            if self.source.consume("|") {
                if sep_seq {
                    return Err(XmlError::SyntaxError {
                        message: "Cannot mix '|' and ',' in the same content group".into(),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
                sep_choice = true;
                self.source.skip_whitespace();
                self.parse_cp()?;
            } else if self.source.consume(",") {
                if sep_choice {
                    return Err(XmlError::SyntaxError {
                        message: "Cannot mix '|' and ',' in the same content group".into(),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
                sep_seq = true;
                self.source.skip_whitespace();
                self.parse_cp()?;
            } else if self.source.consume(")") {
                break;
            } else {
                return Err(XmlError::SyntaxError {
                    message: "Expected '|', ',', or ')' in children group".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
        }

        if let Some(ch) = self.source.peek() {
            if ch == '?' || ch == '*' || ch == '+' {
                self.source.next_char();
            }
        }
        Ok(())
    }

    fn parse_element_contentspec(&mut self) -> Result<()> {
        if self.source.starts_with("EMPTY") {
            let next = self.source.peek_offset(5);
            if next.map_or(true, |c| !is_xml_name_char(c)) {
                self.source.consume("EMPTY");
                return Ok(());
            }
        }
        if self.source.starts_with("ANY") {
            let next = self.source.peek_offset(3);
            if next.map_or(true, |c| !is_xml_name_char(c)) {
                self.source.consume("ANY");
                return Ok(());
            }
        }
        if self.source.peek() == Some('(') {
            let mut offset = 1;
            while let Some(ch) = self.source.peek_offset(offset) {
                if ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' {
                    offset += 1;
                } else {
                    break;
                }
            }
            let is_pcdata = self.source.peek_offset(offset) == Some('#')
                && self.source.peek_offset(offset + 1) == Some('P')
                && self.source.peek_offset(offset + 2) == Some('C')
                && self.source.peek_offset(offset + 3) == Some('D')
                && self.source.peek_offset(offset + 4) == Some('A')
                && self.source.peek_offset(offset + 5) == Some('T')
                && self.source.peek_offset(offset + 6) == Some('A');
            if is_pcdata {
                self.source.consume("(");
                self.source.skip_whitespace();
                self.source.consume("#PCDATA");
                self.parse_mixed()
            } else {
                self.parse_children_group()
            }
        } else {
            Err(XmlError::SyntaxError {
                message: "Invalid element contentspec, expected EMPTY, ANY, or parenthesized model".into(),
                line: self.source.line(),
                col: self.source.col(),
            })
        }
    }

    fn parse_element_decl(&mut self, _subset: &mut String) -> Result<()> {
        if self.source.skip_whitespace() == 0 {
            return Err(XmlError::SyntaxError {
                message: "Whitespace required after '<!ELEMENT'".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        let name = self.parse_name()?;
        if name.is_empty() {
            return Err(XmlError::SyntaxError {
                message: "Expected element name in element declaration".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        if self.source.skip_whitespace() == 0 {
            return Err(XmlError::SyntaxError {
                message: "Whitespace required between element name and contentspec".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        self.parse_element_contentspec()?;
        self.source.skip_whitespace();
        if !self.source.consume(">") {
            return Err(XmlError::SyntaxError {
                message: "Unclosed ELEMENT declaration, expected '>'".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        Ok(())
    }

    fn parse_attlist_decl(&mut self, _subset: &mut String) -> Result<()> {
        if self.source.skip_whitespace() == 0 {
            return Err(XmlError::SyntaxError {
                message: "Whitespace required after '<!ATTLIST'".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        let elem_name = self.parse_name()?;
        if elem_name.is_empty() {
            return Err(XmlError::SyntaxError {
                message: "Expected element name in ATTLIST declaration".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }

        loop {
            let ws = self.source.skip_whitespace();
            if self.source.consume(">") {
                return Ok(());
            }
            if ws == 0 {
                return Err(XmlError::SyntaxError {
                    message: "Whitespace required before attribute definition".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            let att_name = self.parse_name()?;
            if att_name.is_empty() {
                return Err(XmlError::SyntaxError {
                    message: "Expected attribute name in ATTLIST declaration".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            if self.source.skip_whitespace() == 0 {
                return Err(XmlError::SyntaxError {
                    message: "Whitespace required after attribute name".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }

            if self.source.consume("CDATA") {
                // ok
            } else if self.source.consume("IDREFS") {
                // ok
            } else if self.source.consume("IDREF") {
                // ok
            } else if self.source.consume("ID") {
                // ok
            } else if self.source.consume("ENTITIES") {
                // ok
            } else if self.source.consume("ENTITY") {
                // ok
            } else if self.source.consume("NMTOKENS") {
                // ok
            } else if self.source.consume("NMTOKEN") {
                // ok
            } else if self.source.consume("NOTATION") {
                if self.source.skip_whitespace() == 0 {
                    return Err(XmlError::SyntaxError {
                        message: "Whitespace required after 'NOTATION'".into(),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
                if !self.source.consume("(") {
                    return Err(XmlError::SyntaxError {
                        message: "Expected '(' after NOTATION".into(),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
                self.source.skip_whitespace();
                let first_not = self.parse_name()?;
                if first_not.is_empty() {
                    return Err(XmlError::SyntaxError {
                        message: "Expected notation name in NOTATION enumeration".into(),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
                loop {
                    self.source.skip_whitespace();
                    if self.source.consume("|") {
                        self.source.skip_whitespace();
                        let not = self.parse_name()?;
                        if not.is_empty() {
                            return Err(XmlError::SyntaxError {
                                message: "Expected notation name after '|'".into(),
                                line: self.source.line(),
                                col: self.source.col(),
                            });
                        }
                    } else if self.source.consume(")") {
                        break;
                    } else {
                        return Err(XmlError::SyntaxError {
                            message: "Expected '|' or ')' in NOTATION enumeration".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                }
            } else if self.source.peek() == Some('(') {
                self.source.next_char();
                self.source.skip_whitespace();
                let first_tok = self.parse_nmtoken()?;
                if first_tok.is_empty() {
                    return Err(XmlError::SyntaxError {
                        message: "Expected Nmtoken in enumeration".into(),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
                loop {
                    self.source.skip_whitespace();
                    if self.source.consume("|") {
                        self.source.skip_whitespace();
                        let tok = self.parse_nmtoken()?;
                        if tok.is_empty() {
                            return Err(XmlError::SyntaxError {
                                message: "Expected Nmtoken after '|' in enumeration".into(),
                                line: self.source.line(),
                                col: self.source.col(),
                            });
                        }
                    } else if self.source.consume(")") {
                        break;
                    } else {
                        return Err(XmlError::SyntaxError {
                            message: "Expected '|' or ')' in enumeration".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                }
            } else {
                return Err(XmlError::SyntaxError {
                    message: "Invalid attribute type in ATTLIST declaration".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }

            if self.source.skip_whitespace() == 0 {
                return Err(XmlError::SyntaxError {
                    message: "Whitespace required before DefaultDecl in ATTLIST".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            if self.source.consume("#REQUIRED") {
                // ok
            } else if self.source.consume("#IMPLIED") {
                // ok
            } else if self.source.consume("#FIXED") {
                if self.source.skip_whitespace() == 0 {
                    return Err(XmlError::SyntaxError {
                        message: "Whitespace required after '#FIXED'".into(),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
                let val = self.parse_quoted_string()?;
                self.validate_attribute_default_value(&val)?;
            } else if let Some(ch) = self.source.peek() {
                if ch == '"' || ch == '\'' {
                    let val = self.parse_quoted_string()?;
                    self.validate_attribute_default_value(&val)?;
                } else {
                    return Err(XmlError::SyntaxError {
                        message: "Invalid DefaultDecl in ATTLIST declaration".into(),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
            } else {
                return Err(XmlError::SyntaxError {
                    message: "Unexpected end of input in ATTLIST declaration".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
        }
    }

    fn parse_entity_decl(&mut self, subset: &mut String) -> Result<()> {
        if self.source.skip_whitespace() == 0 {
            return Err(XmlError::SyntaxError {
                message: "Whitespace required after '<!ENTITY'".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        let is_param = if self.source.consume("%") {
            if self.source.skip_whitespace() == 0 {
                return Err(XmlError::SyntaxError {
                    message: "Whitespace required after '%' in parameter entity decl".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            true
        } else {
            false
        };
        let name = self.parse_name()?;
        if name.is_empty() {
            return Err(XmlError::SyntaxError {
                message: "Expected entity name in entity declaration".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        if self.source.skip_whitespace() == 0 {
            return Err(XmlError::SyntaxError {
                message: "Whitespace required after entity name".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }

        if self.source.consume("SYSTEM") {
            if self.source.skip_whitespace() == 0 {
                return Err(XmlError::SyntaxError {
                    message: "Whitespace required after 'SYSTEM'".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            let _sys_lit = self.parse_quoted_string()?;
            self.external_entities.push(name.clone());
            if !is_param {
                let ws = self.source.skip_whitespace();
                if self.source.consume("NDATA") {
                    if ws == 0 {
                        return Err(XmlError::SyntaxError {
                            message: "Whitespace required before 'NDATA'".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                    if self.source.skip_whitespace() == 0 {
                        return Err(XmlError::SyntaxError {
                            message: "Whitespace required after 'NDATA'".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                    let ndata_name = self.parse_name()?;
                    if ndata_name.is_empty() {
                        return Err(XmlError::SyntaxError {
                            message: "Expected notation name after 'NDATA'".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                    self.unparsed_entities.push(name.clone());
                } else if self.source.consume("ndata") {
                    return Err(XmlError::SyntaxError {
                        message: "'NDATA' must be uppercase".into(),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
            } else {
                self.source.skip_whitespace();
                if self.source.consume("NDATA") || self.source.consume("ndata") {
                    return Err(XmlError::SyntaxError {
                        message: "Parameter entities cannot have NDataDecl".into(),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
            }
        } else if self.source.consume("PUBLIC") {
            if self.source.skip_whitespace() == 0 {
                return Err(XmlError::SyntaxError {
                    message: "Whitespace required after 'PUBLIC'".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            let _pub_lit = self.parse_pubid_literal()?;
            if self.source.skip_whitespace() == 0 {
                return Err(XmlError::SyntaxError {
                    message: "Whitespace required between Public ID and System ID".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            let _sys_lit = self.parse_quoted_string()?;
            self.external_entities.push(name.clone());
            if !is_param {
                let ws = self.source.skip_whitespace();
                if self.source.consume("NDATA") {
                    if ws == 0 {
                        return Err(XmlError::SyntaxError {
                            message: "Whitespace required before 'NDATA'".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                    if self.source.skip_whitespace() == 0 {
                        return Err(XmlError::SyntaxError {
                            message: "Whitespace required after 'NDATA'".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                    let ndata_name = self.parse_name()?;
                    if ndata_name.is_empty() {
                        return Err(XmlError::SyntaxError {
                            message: "Expected notation name after 'NDATA'".into(),
                            line: self.source.line(),
                            col: self.source.col(),
                        });
                    }
                    self.unparsed_entities.push(name.clone());
                } else if self.source.consume("ndata") {
                    return Err(XmlError::SyntaxError {
                        message: "'NDATA' must be uppercase".into(),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
            } else {
                self.source.skip_whitespace();
                if self.source.consume("NDATA") || self.source.consume("ndata") {
                    return Err(XmlError::SyntaxError {
                        message: "Parameter entities cannot have NDataDecl".into(),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
            }
        } else if let Some(ch) = self.source.peek() {
            if ch == '"' || ch == '\'' {
                let val = self.parse_entity_value()?;
                if !is_param {
                    self.entity_mapper.register(&name, &val);
                    subset.push_str(&format!("<!ENTITY {} \"{}\">", name, val.replace('"', "&quot;")));
                } else {
                    subset.push_str(&format!("<!ENTITY % {} \"{}\">", name, val.replace('"', "&quot;")));
                }
            } else {
                return Err(XmlError::SyntaxError {
                    message: "Expected EntityValue, SYSTEM, or PUBLIC in entity declaration".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
        } else {
            return Err(XmlError::SyntaxError {
                message: "Unexpected end of input in entity declaration".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }

        self.source.skip_whitespace();
        if !self.source.consume(">") {
            return Err(XmlError::SyntaxError {
                message: "Unclosed ENTITY declaration, expected '>'".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        Ok(())
    }

    fn check_attribute_entities(&self, text: &str) -> Result<()> {
        let mut pos = 0;
        let bytes = text.as_bytes();
        while pos < bytes.len() {
            if bytes[pos] == b'&' {
                if let Some(semi_offset) = text[pos..].find(';') {
                    let semi_idx = pos + semi_offset;
                    let ref_name = &text[pos + 1..semi_idx];
                    if !ref_name.starts_with('#') {
                        self.check_entity_for_attribute(ref_name, 0)?;
                    }
                    pos = semi_idx + 1;
                } else {
                    pos += 1;
                }
            } else {
                pos += 1;
            }
        }
        Ok(())
    }

    fn check_entity_for_attribute(&self, name: &str, depth: usize) -> Result<()> {
        if depth > 100 {
            return Err(XmlError::SyntaxError {
                message: "Circular entity reference in attribute".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        if self.unparsed_entities.iter().any(|u| u == name) {
            return Err(XmlError::SyntaxError {
                message: format!("Unparsed entity '{name}' cannot be referenced in attribute"),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        if self.external_entities.iter().any(|e| e == name) {
            return Err(XmlError::SyntaxError {
                message: format!("Attribute values must not contain references to external entity '&{name};'"),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        if name != "lt" && name != "gt" && name != "amp" && name != "quot" && name != "apos" {
            if let Some(val) = self.entity_mapper.get(name) {
                if val.contains('<') {
                    return Err(XmlError::SyntaxError {
                        message: format!("Replacement text of entity '{name}' in attribute contains '<' (WFC: No < in Attribute Values)"),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
                let mut pos = 0;
                let bytes = val.as_bytes();
                while pos < bytes.len() {
                    if bytes[pos] == b'&' {
                        if let Some(semi_offset) = val[pos..].find(';') {
                            let semi_idx = pos + semi_offset;
                            let inner_ref = &val[pos + 1..semi_idx];
                            if !inner_ref.starts_with('#') {
                                self.check_entity_for_attribute(inner_ref, depth + 1)?;
                            }
                            pos = semi_idx + 1;
                        } else {
                            pos += 1;
                        }
                    } else {
                        pos += 1;
                    }
                }
            }
        }
        Ok(())
    }

    fn validate_attribute_default_value(&self, val: &str) -> Result<()> {
        if val.contains('<') {
            return Err(XmlError::SyntaxError {
                message: "Attribute default value cannot contain '<'".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        self.check_attribute_entities(val)?;
        let has_pe = self.entity_mapper.allow_undeclared;
        if !has_pe {
            let mut pos = 0;
            let bytes = val.as_bytes();
            while pos < bytes.len() {
                if bytes[pos] == b'&' {
                    if let Some(semi_offset) = val[pos..].find(';') {
                        let semi_idx = pos + semi_offset;
                        let ref_name = &val[pos + 1..semi_idx];
                        if !ref_name.starts_with('#') {
                            match ref_name {
                                "lt" | "gt" | "amp" | "quot" | "apos" => {}
                                other => {
                                    if self.entity_mapper.get(other).is_none() {
                                        return Err(XmlError::SyntaxError {
                                            message: format!("Entity '{other}' referenced in attribute default before it was declared"),
                                            line: self.source.line(),
                                            col: self.source.col(),
                                        });
                                    }
                                }
                            }
                        }
                        pos = semi_idx + 1;
                    } else {
                        pos += 1;
                    }
                } else {
                    pos += 1;
                }
            }
        }
        let expanded = self.entity_mapper.expand(val)?;
        if expanded.contains('<') {
            return Err(XmlError::SyntaxError {
                message: "Replacement text of entity in attribute default contains '<'".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        Ok(())
    }

    fn validate_entity_replacement_text(&self, name: &str, val: &str) -> Result<()> {
        if val.contains("<?xml") {
            return Err(XmlError::SyntaxError {
                message: format!("'<?xml' forbidden in internal entity '{name}' replacement text"),
                line: self.source.line(),
                col: self.source.col(),
            });
        }

        let mut i = 0;
        let bytes = val.as_bytes();
        while i < bytes.len() {
            if bytes[i] == b'&' {
                if let Some(semi_pos) = val[i..].find(';') {
                    let ref_content = &val[i + 1..i + semi_pos];
                    if ref_content.starts_with('#') {
                        let code_str = &ref_content[1..];
                        let valid = if let Some(hex_digits) = code_str.strip_prefix('x') {
                            !hex_digits.is_empty() && hex_digits.chars().all(|c| c.is_ascii_hexdigit())
                        } else {
                            !code_str.is_empty() && code_str.chars().all(|c| c.is_ascii_digit())
                        };
                        if !valid {
                            return Err(XmlError::SyntaxError {
                                message: format!("Invalid numeric character reference in entity '{name}'"),
                                line: self.source.line(),
                                col: self.source.col(),
                            });
                        }
                    } else {
                        let mut chars = ref_content.chars();
                        let valid = match chars.next() {
                            Some(first) => is_xml_name_start(first) && chars.all(is_xml_name_char),
                            None => false,
                        };
                        if !valid {
                            return Err(XmlError::SyntaxError {
                                message: format!("Invalid entity reference name in entity '{name}'"),
                                line: self.source.line(),
                                col: self.source.col(),
                            });
                        }
                    }
                    i += semi_pos + 1;
                } else {
                    return Err(XmlError::SyntaxError {
                        message: format!("Unclosed '&' in entity '{name}' replacement text (WFC: Parsed Entity)"),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
            } else {
                i += 1;
            }
        }

        if val.contains('<') {
            let mut pos = 0;
            let mut tag_stack: Vec<String> = Vec::new();
            while pos < bytes.len() {
                if bytes[pos] == b'<' {
                    let rest = &val[pos..];
                    if rest.starts_with("<!--") {
                        if let Some(end_comment) = rest.find("-->") {
                            pos += end_comment + 3;
                            continue;
                        } else {
                            return Err(XmlError::SyntaxError {
                                message: format!("Unclosed comment in entity '{name}' (WFC: Parsed Entity)"),
                                line: self.source.line(),
                                col: self.source.col(),
                            });
                        }
                    } else if rest.starts_with("<?") {
                        if let Some(end_pi) = rest.find("?>") {
                            pos += end_pi + 2;
                            continue;
                        } else {
                            return Err(XmlError::SyntaxError {
                                message: format!("Unclosed PI in entity '{name}' (WFC: Parsed Entity)"),
                                line: self.source.line(),
                                col: self.source.col(),
                            });
                        }
                    } else if rest.starts_with("<![CDATA[") {
                        if let Some(end_cdata) = rest.find("]]>") {
                            pos += end_cdata + 3;
                            continue;
                        } else {
                            return Err(XmlError::SyntaxError {
                                message: format!("Unclosed CDATA in entity '{name}' (WFC: Parsed Entity)"),
                                line: self.source.line(),
                                col: self.source.col(),
                            });
                        }
                    } else if rest.starts_with("</") {
                        if let Some(gt) = rest.find('>') {
                            let tag_name = rest[2..gt].trim();
                            if let Some(expected) = tag_stack.pop() {
                                if expected != tag_name {
                                    return Err(XmlError::SyntaxError {
                                        message: format!("Mismatched end tag '</{tag_name}>' in entity '{name}', expected '</{expected}>'"),
                                        line: self.source.line(),
                                        col: self.source.col(),
                                    });
                                }
                            } else {
                                return Err(XmlError::SyntaxError {
                                    message: format!("End tag '</{tag_name}>' in entity '{name}' has no matching start tag (WFC: Parsed Entity)"),
                                    line: self.source.line(),
                                    col: self.source.col(),
                                });
                            }
                            pos += gt + 1;
                            continue;
                        } else {
                            return Err(XmlError::SyntaxError {
                                message: format!("Unclosed end tag in entity '{name}'"),
                                line: self.source.line(),
                                col: self.source.col(),
                            });
                        }
                    } else {
                        if let Some(gt) = rest.find('>') {
                            let is_self_closing = rest[..gt].ends_with('/');
                            let tag_body = if is_self_closing {
                                &rest[1..gt - 1]
                            } else {
                                &rest[1..gt]
                            };
                            let elem_tag = tag_body.split_whitespace().next().unwrap_or("");
                            if let Some(first_space) = tag_body.find(|c: char| c.is_whitespace()) {
                                let attrs_part = &tag_body[first_space..];
                                if attrs_part.contains('<') {
                                    return Err(XmlError::SyntaxError {
                                        message: format!("Attribute value cannot contain '<' in entity '{name}'"),
                                        line: self.source.line(),
                                        col: self.source.col(),
                                    });
                                }
                                let mut a_pos = 0;
                                let a_bytes = attrs_part.as_bytes();
                                while a_pos < a_bytes.len() {
                                    if a_bytes[a_pos] == b'&' {
                                        if let Some(semi) = attrs_part[a_pos..].find(';') {
                                            a_pos += semi + 1;
                                        } else {
                                            return Err(XmlError::SyntaxError {
                                                message: format!("Unescaped '&' in attribute in entity '{name}'"),
                                                line: self.source.line(),
                                                col: self.source.col(),
                                            });
                                        }
                                    } else {
                                        a_pos += 1;
                                    }
                                }
                            }
                            if !is_self_closing && !elem_tag.is_empty() {
                                tag_stack.push(elem_tag.to_string());
                            }
                            pos += gt + 1;
                            continue;
                        } else {
                            return Err(XmlError::SyntaxError {
                                message: format!("Unclosed start tag in entity '{name}' (WFC: Parsed Entity)"),
                                line: self.source.line(),
                                col: self.source.col(),
                            });
                        }
                    }
                }
                pos += 1;
            }
            if !tag_stack.is_empty() {
                return Err(XmlError::SyntaxError {
                    message: format!("Unclosed element in entity '{name}' replacement text (WFC: Parsed Entity)"),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
        }

        Ok(())
    }

    fn parse_notation_decl(&mut self, _subset: &mut String) -> Result<()> {
        if self.source.skip_whitespace() == 0 {
            return Err(XmlError::SyntaxError {
                message: "Whitespace required after '<!NOTATION'".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        let name = self.parse_name()?;
        if name.is_empty() {
            return Err(XmlError::SyntaxError {
                message: "Expected notation name".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        if self.source.skip_whitespace() == 0 {
            return Err(XmlError::SyntaxError {
                message: "Whitespace required after notation name".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        if self.source.consume("SYSTEM") {
            if self.source.skip_whitespace() == 0 {
                return Err(XmlError::SyntaxError {
                    message: "Whitespace required after 'SYSTEM'".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            let _sys = self.parse_quoted_string()?;
        } else if self.source.consume("PUBLIC") {
            if self.source.skip_whitespace() == 0 {
                return Err(XmlError::SyntaxError {
                    message: "Whitespace required after 'PUBLIC'".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
            let _pub = self.parse_pubid_literal()?;
            if self.source.skip_whitespace() > 0 {
                if let Some(ch) = self.source.peek() {
                    if ch == '"' || ch == '\'' {
                        let _sys = self.parse_quoted_string()?;
                    }
                }
            }
        } else {
            return Err(XmlError::SyntaxError {
                message: "Expected SYSTEM or PUBLIC in notation declaration".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }

        self.source.skip_whitespace();
        if !self.source.consume(">") {
            return Err(XmlError::SyntaxError {
                message: "Unclosed NOTATION declaration, expected '>'".into(),
                line: self.source.line(),
                col: self.source.col(),
            });
        }
        Ok(())
    }

    fn parse_internal_subset(&mut self) -> Result<String> {
        let start = self.source.position();
        let mut subset = String::new();
        loop {
            self.source.skip_whitespace();
            if self.source.peek() == Some(']') {
                let end = self.source.position();
                self.source.next_char();
                return Ok(self.source.slice_range(start, end).to_string());
            }
            if self.source.starts_with("<!--") {
                let mut dummy_doc = Document::new();
                self.parse_comment(&mut dummy_doc)?;
            } else if self.source.starts_with("<?") {
                let mut dummy_doc = Document::new();
                self.parse_pi(&mut dummy_doc)?;
            } else if self.source.starts_with("<!ELEMENT") {
                self.source.consume("<!ELEMENT");
                self.parse_element_decl(&mut subset)?;
            } else if self.source.starts_with("<!ATTLIST") {
                self.source.consume("<!ATTLIST");
                self.parse_attlist_decl(&mut subset)?;
            } else if self.source.starts_with("<!ENTITY") {
                self.source.consume("<!ENTITY");
                self.parse_entity_decl(&mut subset)?;
            } else if self.source.starts_with("<!NOTATION") {
                self.source.consume("<!NOTATION");
                self.parse_notation_decl(&mut subset)?;
            } else if self.source.starts_with("%") {
                self.source.next_char();
                let name = self.parse_name()?;
                if name.is_empty() {
                    return Err(XmlError::SyntaxError {
                        message: "Expected Name in parameter entity reference".into(),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
                if !self.source.consume(";") {
                    return Err(XmlError::SyntaxError {
                        message: "Expected ';' in parameter entity reference".into(),
                        line: self.source.line(),
                        col: self.source.col(),
                    });
                }
            } else if self.source.starts_with("<!") {
                return Err(XmlError::SyntaxError {
                    message: "Invalid markup declaration in internal subset".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            } else if self.source.is_eof() {
                return Err(XmlError::SyntaxError {
                    message: "Unclosed internal DTD subset, expected ']'".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            } else {
                return Err(XmlError::SyntaxError {
                    message: "Unexpected character in internal DTD subset".into(),
                    line: self.source.line(),
                    col: self.source.col(),
                });
            }
        }
    }
}