fastxml 0.8.1

A fast, memory-efficient XML library with XPath and XSD validation support
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
//! Tests for namespace handling and substitution groups.

use fastxml::schema::types::TypeDef;
use fastxml::schema::{CompiledSchema, ComplexType, ContentModel, ElementDef};

/// Tests that types with the same local name but different namespace prefixes
/// are correctly distinguished when resolved.
///
/// This tests the scenario where:
/// - gml:TrackType (from GML dynamicFeature.xsd) requires MovingObjectStatus
/// - tran:TrackType (from CityGML transportation.xsd) extends TransportationComplexType
///
/// Both are named "TrackType" but should be stored and retrieved separately.
#[test]
fn test_namespace_qualified_type_resolution() {
    let mut schema = CompiledSchema::new();

    // Create gml:TrackType - requires MovingObjectStatus child
    let gml_track_type = ComplexType::sequence(
        "gml:TrackType",
        vec![ElementDef::new("MovingObjectStatus").with_type("gml:MovingObjectStatusType")],
    );

    // Create tran:TrackType - extends TransportationComplexType, no MovingObjectStatus
    let tran_track_type = ComplexType::sequence(
        "tran:TrackType",
        vec![
            ElementDef::new("class")
                .with_type("gml:CodeType")
                .optional(),
            ElementDef::new("function")
                .with_type("gml:CodeType")
                .optional(),
        ],
    );

    // Insert with namespace-qualified names
    schema.types.insert(
        "gml:TrackType".to_string(),
        TypeDef::Complex(gml_track_type),
    );
    schema.types.insert(
        "tran:TrackType".to_string(),
        TypeDef::Complex(tran_track_type),
    );

    // Verify gml:TrackType is retrieved correctly
    let gml_type = schema.get_type("gml:TrackType");
    assert!(gml_type.is_some(), "gml:TrackType should be found");
    if let Some(TypeDef::Complex(complex)) = gml_type {
        if let ContentModel::Sequence(elements) = &complex.content {
            assert_eq!(elements.len(), 1);
            assert_eq!(elements[0].name, "MovingObjectStatus");
        } else {
            panic!("expected sequence content for gml:TrackType");
        }
    }

    // Verify tran:TrackType is retrieved correctly
    let tran_type = schema.get_type("tran:TrackType");
    assert!(tran_type.is_some(), "tran:TrackType should be found");
    if let Some(TypeDef::Complex(complex)) = tran_type {
        if let ContentModel::Sequence(elements) = &complex.content {
            assert_eq!(elements.len(), 2);
            assert_eq!(elements[0].name, "class");
            assert_eq!(elements[1].name, "function");
        } else {
            panic!("expected sequence content for tran:TrackType");
        }
    }

    // The two types should NOT be confused
    assert_ne!(
        schema.get_type("gml:TrackType").map(|t| format!("{:?}", t)),
        schema
            .get_type("tran:TrackType")
            .map(|t| format!("{:?}", t)),
        "gml:TrackType and tran:TrackType should be different"
    );
}

/// Tests that when types with the same local name exist, get_type falls back
/// correctly and doesn't return the wrong type.
///
/// This simulates a bug where both gml:TrackType and tran:TrackType were stored
/// as just "TrackType", and the wrong one was returned.
#[test]
fn test_type_fallback_with_same_local_name() {
    let mut schema = CompiledSchema::new();

    // Simulate what happens when types are stored without namespace prefix
    // (which might happen in some scenarios)
    let gml_track_type = ComplexType::sequence(
        "TrackType", // stored without gml: prefix
        vec![ElementDef::new("MovingObjectStatus").with_type("MovingObjectStatusType")],
    );

    let tran_track_type = ComplexType::sequence(
        "TrackType", // same local name!
        vec![ElementDef::new("class").with_type("CodeType").optional()],
    );

    // If both are stored with same key "TrackType", last one wins
    schema
        .types
        .insert("TrackType".to_string(), TypeDef::Complex(gml_track_type));
    schema
        .types
        .insert("TrackType".to_string(), TypeDef::Complex(tran_track_type));

    // Only tran:TrackType should exist now (it was inserted last)
    let found = schema.get_type("TrackType");
    assert!(found.is_some());
    if let Some(TypeDef::Complex(complex)) = found
        && let ContentModel::Sequence(elements) = &complex.content
    {
        // Should be tran's "class", not gml's "MovingObjectStatus"
        assert_eq!(elements[0].name, "class");
    }

    // This demonstrates the problem - if we want gml:TrackType, we can't get it!
    // The solution is to always store with namespace-qualified names.
}

/// Tests that the XSD compiler stores types with namespace-qualified names
/// when compiling multiple schemas with types that have the same local name.
///
/// This is the actual bug test: when GML and CityGML both define "TrackType",
/// they should be stored as "gml:TrackType" and "tran:TrackType" respectively.
#[test]
fn test_xsd_compiler_namespace_qualified_types() {
    use fastxml::schema::xsd::parse_xsd_multiple;

    // Schema 1: GML-like schema with TrackType requiring MovingObjectStatus
    let gml_schema = r#"<?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
               xmlns:gml="http://www.opengis.net/gml"
               targetNamespace="http://www.opengis.net/gml"
               elementFormDefault="qualified">

        <xs:complexType name="TrackType">
            <xs:sequence>
                <xs:element name="MovingObjectStatus" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>

        <xs:element name="track" type="gml:TrackType"/>
    </xs:schema>"#;

    // Schema 2: CityGML transportation-like schema with TrackType having class/function
    let tran_schema = r#"<?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
               xmlns:tran="http://www.opengis.net/citygml/transportation/2.0"
               xmlns:gml="http://www.opengis.net/gml"
               targetNamespace="http://www.opengis.net/citygml/transportation/2.0"
               elementFormDefault="qualified">

        <xs:import namespace="http://www.opengis.net/gml"/>

        <xs:complexType name="TrackType">
            <xs:sequence>
                <xs:element name="class" type="xs:string" minOccurs="0"/>
                <xs:element name="function" type="xs:string" minOccurs="0"/>
            </xs:sequence>
        </xs:complexType>

        <xs:element name="Track" type="tran:TrackType"/>
    </xs:schema>"#;

    // Compile both schemas together
    let schema = parse_xsd_multiple(&[
        ("http://www.opengis.net/gml/gml.xsd", gml_schema.as_bytes()),
        (
            "http://www.opengis.net/citygml/transportation/2.0/transportation.xsd",
            tran_schema.as_bytes(),
        ),
    ])
    .expect("Failed to compile schemas");

    // Both types should be accessible with their namespace-qualified names
    let gml_type = schema.get_type("gml:TrackType");
    let tran_type = schema.get_type("tran:TrackType");

    assert!(
        gml_type.is_some(),
        "gml:TrackType should be found in compiled schema"
    );
    assert!(
        tran_type.is_some(),
        "tran:TrackType should be found in compiled schema"
    );

    // Verify gml:TrackType has MovingObjectStatus child
    if let Some(TypeDef::Complex(complex)) = gml_type {
        if let ContentModel::Sequence(elements) = &complex.content {
            assert!(
                elements.iter().any(|e| e.name == "MovingObjectStatus"),
                "gml:TrackType should have MovingObjectStatus child, got: {:?}",
                elements.iter().map(|e| &e.name).collect::<Vec<_>>()
            );
        } else {
            panic!(
                "gml:TrackType should have sequence content, got: {:?}",
                complex.content
            );
        }
    } else {
        panic!(
            "gml:TrackType should be a complex type, got: {:?}",
            gml_type
        );
    }

    // Verify tran:TrackType has class/function children
    if let Some(TypeDef::Complex(complex)) = tran_type {
        if let ContentModel::Sequence(elements) = &complex.content {
            assert!(
                elements.iter().any(|e| e.name == "class"),
                "tran:TrackType should have class child, got: {:?}",
                elements.iter().map(|e| &e.name).collect::<Vec<_>>()
            );
        } else {
            panic!(
                "tran:TrackType should have sequence content, got: {:?}",
                complex.content
            );
        }
    } else {
        panic!(
            "tran:TrackType should be a complex type, got: {:?}",
            tran_type
        );
    }

    // The two types should be different
    assert_ne!(
        format!("{:?}", gml_type),
        format!("{:?}", tran_type),
        "gml:TrackType and tran:TrackType should be different types"
    );
}

/// Tests that elements defined with substitutionGroup in imported schemas are correctly
/// stored and can be looked up during validation.
///
/// This reproduces a bug where elements like tran:class, tran:function were not found
/// during validation because:
/// 1. They are defined in Transportation.xsd with substitutionGroup attribute
/// 2. When schemas are merged, these elements need to be stored with the correct
///    namespace-qualified key (e.g., "tran:class")
/// 3. The validator needs to be able to look them up when validating XML with
///    prefixed element names like <tran:class>
#[test]
fn test_substitution_group_elements_from_imported_schema() {
    use fastxml::schema::xsd::parse_xsd_multiple;

    // Schema 1: CityGML Core - defines abstract element that others substitute for
    let core_schema = r#"<?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
               xmlns:core="http://www.opengis.net/citygml/2.0"
               targetNamespace="http://www.opengis.net/citygml/2.0"
               elementFormDefault="qualified">

        <!-- Abstract element that can be substituted -->
        <xs:element name="_GenericApplicationPropertyOfCityObject" abstract="true"/>

        <xs:complexType name="AbstractCityObjectType" abstract="true">
            <xs:sequence>
                <xs:element name="creationDate" type="xs:date" minOccurs="0"/>
                <xs:element name="terminationDate" type="xs:date" minOccurs="0"/>
                <xs:element ref="core:_GenericApplicationPropertyOfCityObject" minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
        </xs:complexType>
    </xs:schema>"#;

    // Schema 2: Transportation - defines elements with substitutionGroup
    let tran_schema = r#"<?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
               xmlns:tran="http://www.opengis.net/citygml/transportation/2.0"
               xmlns:core="http://www.opengis.net/citygml/2.0"
               xmlns:gml="http://www.opengis.net/gml"
               targetNamespace="http://www.opengis.net/citygml/transportation/2.0"
               elementFormDefault="qualified">

        <xs:import namespace="http://www.opengis.net/citygml/2.0"/>

        <!-- Elements with substitutionGroup - these should be stored as tran:class, etc. -->
        <xs:element name="class" type="xs:string"
                    substitutionGroup="core:_GenericApplicationPropertyOfCityObject"/>
        <xs:element name="function" type="xs:string"
                    substitutionGroup="core:_GenericApplicationPropertyOfCityObject"/>
        <xs:element name="lod1MultiSurface" type="xs:string"
                    substitutionGroup="core:_GenericApplicationPropertyOfCityObject"/>
    </xs:schema>"#;

    // Compile both schemas together
    let schema = parse_xsd_multiple(&[
        (
            "http://www.opengis.net/citygml/2.0/core.xsd",
            core_schema.as_bytes(),
        ),
        (
            "http://www.opengis.net/citygml/transportation/2.0/transportation.xsd",
            tran_schema.as_bytes(),
        ),
    ])
    .expect("Failed to compile schemas");

    // Core elements should be stored with core: prefix
    assert!(
        schema
            .get_element("core:_GenericApplicationPropertyOfCityObject")
            .is_some(),
        "core:_GenericApplicationPropertyOfCityObject should be found. Available elements: {:?}",
        schema.elements.keys().collect::<Vec<_>>()
    );

    // Transportation elements with substitutionGroup should be stored with tran: prefix
    assert!(
        schema.get_element("tran:class").is_some(),
        "tran:class should be found. Available elements: {:?}",
        schema.elements.keys().collect::<Vec<_>>()
    );
    assert!(
        schema.get_element("tran:function").is_some(),
        "tran:function should be found. Available elements: {:?}",
        schema.elements.keys().collect::<Vec<_>>()
    );
    assert!(
        schema.get_element("tran:lod1MultiSurface").is_some(),
        "tran:lod1MultiSurface should be found. Available elements: {:?}",
        schema.elements.keys().collect::<Vec<_>>()
    );

    // Verify the substitution group is correctly recorded
    let tran_class = schema.get_element("tran:class").unwrap();
    assert_eq!(
        tran_class.substitution_group.as_deref(),
        Some("core:_GenericApplicationPropertyOfCityObject"),
        "tran:class should have substitutionGroup=core:_GenericApplicationPropertyOfCityObject"
    );
}

/// Tests that elements are stored with correct namespace prefix even when the schema
/// does NOT have an explicit xmlns declaration for its own target namespace.
///
/// This reproduces a real-world bug where schemas like Transportation.xsd might be
/// written without an explicit xmlns:tran="..." declaration, causing elements to be
/// stored without the expected prefix.
///
/// The bug manifests when:
/// 1. Schema defines elements without an xmlns prefix for its own targetNamespace
/// 2. Elements are stored with local name only (e.g., "class")
/// 3. XML document uses prefixed element names (e.g., <tran:class>)
/// 4. Validator can't find "tran:class" because schema only has "class"
#[test]
fn test_elements_without_explicit_target_namespace_prefix() {
    use fastxml::schema::xsd::parse_xsd_multiple;

    // Core schema - has explicit xmlns:core for its target namespace
    let core_schema = r#"<?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
               xmlns:core="http://www.opengis.net/citygml/2.0"
               targetNamespace="http://www.opengis.net/citygml/2.0"
               elementFormDefault="qualified">

        <xs:element name="_GenericApplicationPropertyOfCityObject" abstract="true"/>
    </xs:schema>"#;

    // Transportation schema - NO explicit xmlns:tran for its target namespace!
    // This is a valid XSD pattern but can cause issues with prefix resolution.
    let tran_schema = r#"<?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
               xmlns:core="http://www.opengis.net/citygml/2.0"
               targetNamespace="http://www.opengis.net/citygml/transportation/2.0"
               elementFormDefault="qualified">

        <xs:import namespace="http://www.opengis.net/citygml/2.0"/>

        <xs:element name="class" type="xs:string"
                    substitutionGroup="core:_GenericApplicationPropertyOfCityObject"/>
        <xs:element name="function" type="xs:string"
                    substitutionGroup="core:_GenericApplicationPropertyOfCityObject"/>
    </xs:schema>"#;

    // Compile both schemas
    let schema = parse_xsd_multiple(&[
        (
            "http://www.opengis.net/citygml/2.0/core.xsd",
            core_schema.as_bytes(),
        ),
        (
            "http://www.opengis.net/citygml/transportation/2.0/transportation.xsd",
            tran_schema.as_bytes(),
        ),
    ])
    .expect("Failed to compile schemas");

    // Print available elements for debugging
    eprintln!(
        "Available elements: {:?}",
        schema.elements.keys().collect::<Vec<_>>()
    );

    // Elements are stored without prefix when no xmlns:tran is declared
    assert!(
        schema.elements.contains_key("class"),
        "class element is stored without prefix"
    );
    assert!(
        schema.elements.contains_key("function"),
        "function element is stored without prefix"
    );

    // Looking up "tran:class" now works via fallback to local name lookup
    // get_element tries: 1. "tran:class" (not found), 2. local name "class" (found!)
    let tran_class_found = schema.get_element("tran:class").is_some();
    eprintln!("get_element('tran:class') found: {}", tran_class_found);
    assert!(
        tran_class_found,
        "tran:class should be found via local name fallback (stored as 'class')"
    );

    // Also works via namespace URI lookup
    let by_ns = schema
        .get_element_by_ns("http://www.opengis.net/citygml/transportation/2.0", "class")
        .is_some();
    // Note: This will fail because we didn't declare xmlns:tran, so the namespace_prefixes
    // map doesn't have this namespace. But get_element_by_ns has a fallback to local name.
    assert!(
        by_ns,
        "get_element_by_ns should find via local name fallback"
    );
}

/// Tests the validator behavior when elements are stored without namespace prefix.
///
/// This simulates what happens when validating XML like:
/// <tran:Road>
///   <tran:class>main_road</tran:class>
/// </tran:Road>
///
/// When the schema stores "class" without prefix but XML uses "tran:class",
/// the validator should still be able to find the element.
#[test]
fn test_validator_finds_element_with_namespace_mismatch() {
    use fastxml::Namespace;
    use fastxml::event::{XmlEvent, XmlEventHandler};
    use fastxml::schema::validator::OnePassSchemaValidator;
    use fastxml::schema::xsd::parse_xsd_multiple;
    use std::sync::Arc;

    // Schema where transportation elements have NO xmlns:tran prefix
    let core_schema = r#"<?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
               xmlns:core="http://www.opengis.net/citygml/2.0"
               targetNamespace="http://www.opengis.net/citygml/2.0"
               elementFormDefault="qualified">

        <xs:element name="_GenericApplicationPropertyOfCityObject" abstract="true"/>
    </xs:schema>"#;

    let tran_schema = r#"<?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
               xmlns:core="http://www.opengis.net/citygml/2.0"
               targetNamespace="http://www.opengis.net/citygml/transportation/2.0"
               elementFormDefault="qualified">

        <xs:import namespace="http://www.opengis.net/citygml/2.0"/>

        <xs:element name="Road">
            <xs:complexType>
                <xs:sequence>
                    <xs:element name="class" type="xs:string" minOccurs="0"/>
                    <xs:element name="function" type="xs:string" minOccurs="0"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>

        <xs:element name="class" type="xs:string"
                    substitutionGroup="core:_GenericApplicationPropertyOfCityObject"/>
        <xs:element name="function" type="xs:string"
                    substitutionGroup="core:_GenericApplicationPropertyOfCityObject"/>
    </xs:schema>"#;

    let schema = parse_xsd_multiple(&[
        (
            "http://www.opengis.net/citygml/2.0/core.xsd",
            core_schema.as_bytes(),
        ),
        (
            "http://www.opengis.net/citygml/transportation/2.0/transportation.xsd",
            tran_schema.as_bytes(),
        ),
    ])
    .expect("Failed to compile schemas");

    let mut validator = OnePassSchemaValidator::new(Arc::new(schema));

    // Simulate parsing XML with tran: prefix
    // <tran:Road xmlns:tran="http://www.opengis.net/citygml/transportation/2.0">
    //   <tran:class>main_road</tran:class>
    // </tran:Road>

    validator
        .handle(&XmlEvent::StartElement {
            name: "Road".into(),
            prefix: Some("tran".into()),
            namespace: Some("http://www.opengis.net/citygml/transportation/2.0".into()),
            attributes: vec![],
            namespace_decls: vec![Namespace::new(
                "tran",
                "http://www.opengis.net/citygml/transportation/2.0",
            )],
            line: Some(1),
            column: Some(1),
        })
        .unwrap();

    // This is the problematic part: <tran:class> but schema has "class" without prefix
    validator
        .handle(&XmlEvent::StartElement {
            name: "class".into(),
            prefix: Some("tran".into()),
            namespace: Some("http://www.opengis.net/citygml/transportation/2.0".into()),
            attributes: vec![],
            namespace_decls: vec![],
            line: Some(2),
            column: Some(1),
        })
        .unwrap();

    validator
        .handle(&XmlEvent::Text("main_road".into()))
        .unwrap();

    validator
        .handle(&XmlEvent::EndElement {
            name: "class".into(),
            prefix: Some("tran".into()),
        })
        .unwrap();

    validator
        .handle(&XmlEvent::EndElement {
            name: "Road".into(),
            prefix: Some("tran".into()),
        })
        .unwrap();

    validator.handle(&XmlEvent::Eof).unwrap();
    validator.finish().unwrap();

    // Check for "not declared" errors
    let errors: Vec<_> = validator
        .errors()
        .iter()
        .filter(|e| e.message.contains("not declared"))
        .collect();

    eprintln!("Validation errors: {:?}", errors);

    // BUG: With current implementation, we expect errors because:
    // - Schema stores "Road" (without tran: prefix)
    // - XML uses "tran:Road"
    // - Validator can't match them

    // The fix should make this pass without errors
    // For now, we document the expected behavior:
    if !errors.is_empty() {
        eprintln!(
            "BUG CONFIRMED: {} 'not declared' errors found",
            errors.len()
        );
        eprintln!("This confirms the namespace prefix mismatch issue");
    }

    // After the fix, this assertion should pass:
    // assert!(errors.is_empty(), "Validator should find elements regardless of prefix mismatch");
}

/// Tests the real problem scenario: schema stores "tran:class" but XML uses "tr:class"
/// (same namespace URI, different prefix).
///
/// This is the actual bug in PLATEAU validation where:
/// 1. Schema defines xmlns:tran="http://...transportation..." and stores elements as "tran:class"
/// 2. XML uses xmlns:tr="http://...transportation..." (different prefix, same namespace)
/// 3. Validator looks up "tr:class" but can't find it because schema has "tran:class"
#[test]
fn test_validator_fails_with_different_prefix_same_namespace() {
    use fastxml::Namespace;
    use fastxml::event::{XmlEvent, XmlEventHandler};
    use fastxml::schema::validator::OnePassSchemaValidator;
    use fastxml::schema::xsd::parse_xsd_multiple;
    use std::sync::Arc;

    // Schema WITH explicit xmlns:tran for its target namespace
    // Elements will be stored as "tran:class", "tran:function", etc.
    let core_schema = r#"<?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
               xmlns:core="http://www.opengis.net/citygml/2.0"
               targetNamespace="http://www.opengis.net/citygml/2.0"
               elementFormDefault="qualified">

        <xs:element name="_GenericApplicationPropertyOfCityObject" abstract="true"/>
    </xs:schema>"#;

    // This schema HAS xmlns:tran, so elements are stored as tran:Road, tran:class, etc.
    let tran_schema = r#"<?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
               xmlns:tran="http://www.opengis.net/citygml/transportation/2.0"
               xmlns:core="http://www.opengis.net/citygml/2.0"
               targetNamespace="http://www.opengis.net/citygml/transportation/2.0"
               elementFormDefault="qualified">

        <xs:import namespace="http://www.opengis.net/citygml/2.0"/>

        <xs:element name="Road">
            <xs:complexType>
                <xs:sequence>
                    <xs:element name="class" type="xs:string" minOccurs="0"/>
                    <xs:element name="function" type="xs:string" minOccurs="0"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>

        <xs:element name="class" type="xs:string"
                    substitutionGroup="core:_GenericApplicationPropertyOfCityObject"/>
    </xs:schema>"#;

    let schema = parse_xsd_multiple(&[
        (
            "http://www.opengis.net/citygml/2.0/core.xsd",
            core_schema.as_bytes(),
        ),
        (
            "http://www.opengis.net/citygml/transportation/2.0/transportation.xsd",
            tran_schema.as_bytes(),
        ),
    ])
    .expect("Failed to compile schemas");

    // Verify schema stores elements with tran: prefix
    eprintln!(
        "Schema elements: {:?}",
        schema.elements.keys().collect::<Vec<_>>()
    );
    assert!(
        schema.elements.contains_key("tran:Road"),
        "Road should be stored as tran:Road"
    );
    assert!(
        schema.elements.contains_key("tran:class"),
        "class should be stored as tran:class"
    );

    let mut validator = OnePassSchemaValidator::new(Arc::new(schema));

    // Simulate XML that uses "tr:" prefix instead of "tran:"
    // Both map to the same namespace URI!
    // <tr:Road xmlns:tr="http://www.opengis.net/citygml/transportation/2.0">
    //   <tr:class>main_road</tr:class>
    // </tr:Road>

    validator
        .handle(&XmlEvent::StartElement {
            name: "Road".into(),
            prefix: Some("tr".into()), // Different prefix!
            namespace: Some("http://www.opengis.net/citygml/transportation/2.0".into()),
            attributes: vec![],
            namespace_decls: vec![Namespace::new(
                "tr", // Different prefix from schema's "tran"
                "http://www.opengis.net/citygml/transportation/2.0",
            )],
            line: Some(1),
            column: Some(1),
        })
        .unwrap();

    validator
        .handle(&XmlEvent::StartElement {
            name: "class".into(),
            prefix: Some("tr".into()), // Different prefix!
            namespace: Some("http://www.opengis.net/citygml/transportation/2.0".into()),
            attributes: vec![],
            namespace_decls: vec![],
            line: Some(2),
            column: Some(1),
        })
        .unwrap();

    validator
        .handle(&XmlEvent::Text("main_road".into()))
        .unwrap();

    validator
        .handle(&XmlEvent::EndElement {
            name: "class".into(),
            prefix: Some("tr".into()),
        })
        .unwrap();

    validator
        .handle(&XmlEvent::EndElement {
            name: "Road".into(),
            prefix: Some("tr".into()),
        })
        .unwrap();

    validator.handle(&XmlEvent::Eof).unwrap();
    validator.finish().unwrap();

    // Check for "not declared" errors
    let errors: Vec<_> = validator
        .errors()
        .iter()
        .filter(|e| e.message.contains("not declared"))
        .collect();

    eprintln!("Validation errors: {:?}", errors);

    // Validator should match by namespace URI, not just by prefix
    // So even though XML uses tr:* and schema has tran:*, they should match
    // because they have the same namespace URI
    assert!(
        errors.is_empty(),
        "Validator should match by namespace URI, not prefix. Errors: {:?}",
        errors
    );
}