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
//! Integration tests for XSD parsing with PLATEAU CityGML data.

use std::sync::Arc;

use fastxml::event::{XmlEvent, XmlEventHandler};
use fastxml::schema::validator::OnePassSchemaValidator;
use fastxml::schema::xsd;

/// Test parsing a simple CityGML-like schema
#[test]
fn test_citygml_schema_parsing() {
    let citygml_like_xsd = 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/3.2"
               xmlns:core="http://www.opengis.net/citygml/2.0"
               targetNamespace="http://www.opengis.net/citygml/relief/2.0"
               elementFormDefault="qualified">

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

        <xs:element name="ReliefFeature" type="ReliefFeatureType" substitutionGroup="core:_CityObject"/>

        <xs:complexType name="ReliefFeatureType">
            <xs:complexContent>
                <xs:extension base="core:AbstractCityObjectType">
                    <xs:sequence>
                        <xs:element name="lod" type="xs:integer"/>
                        <xs:element name="reliefComponent" type="ReliefComponentPropertyType" minOccurs="0" maxOccurs="unbounded"/>
                    </xs:sequence>
                </xs:extension>
            </xs:complexContent>
        </xs:complexType>

        <xs:complexType name="ReliefComponentPropertyType">
            <xs:sequence minOccurs="0">
                <xs:element ref="TINRelief"/>
            </xs:sequence>
            <xs:attributeGroup ref="gml:AssociationAttributeGroup"/>
        </xs:complexType>

        <xs:element name="TINRelief" type="TINReliefType" substitutionGroup="core:_CityObject"/>

        <xs:complexType name="TINReliefType">
            <xs:complexContent>
                <xs:extension base="core:AbstractCityObjectType">
                    <xs:sequence>
                        <xs:element name="lod" type="xs:integer"/>
                        <xs:element name="tin" type="gml:TriangulatedSurfacePropertyType"/>
                    </xs:sequence>
                </xs:extension>
            </xs:complexContent>
        </xs:complexType>

    </xs:schema>"#;

    let schema = xsd::parse_xsd(citygml_like_xsd.as_bytes()).unwrap();

    // Check that elements are parsed
    assert!(schema.elements.contains_key("ReliefFeature"));
    assert!(schema.elements.contains_key("TINRelief"));

    // Check that types are parsed
    assert!(schema.types.contains_key("ReliefFeatureType"));
    assert!(schema.types.contains_key("TINReliefType"));
    assert!(schema.types.contains_key("ReliefComponentPropertyType"));

    // Check that built-in types are available
    assert!(schema.types.contains_key("xs:integer"));
    assert!(schema.types.contains_key("gml:CodeType"));
}

/// Test creating a validation context with built-in types
#[test]
fn test_builtin_schema_validation() {
    let schema = xsd::create_builtin_schema();
    let validator = OnePassSchemaValidator::new(Arc::new(schema));

    // The validator should be valid initially
    assert!(validator.is_valid());
}

/// Test parsing and validating a simple GML document
#[test]
fn test_gml_document_validation() {
    let schema = xsd::create_builtin_schema();
    let mut validator = OnePassSchemaValidator::new(Arc::new(schema));

    // Simulate parsing a GML document
    validator
        .handle(&XmlEvent::StartElement {
            name: "Envelope".into(),
            prefix: Some("gml".into()),
            namespace: Some("http://www.opengis.net/gml/3.2".into()),
            attributes: vec![
                ("srsName".into(), "EPSG:6697".into()),
                ("srsDimension".into(), "3".into()),
            ],
            namespace_decls: vec![],
            line: Some(1),
            column: Some(1),
        })
        .unwrap();

    validator
        .handle(&XmlEvent::StartElement {
            name: "lowerCorner".into(),
            prefix: Some("gml".into()),
            namespace: Some("http://www.opengis.net/gml/3.2".into()),
            attributes: vec![],
            namespace_decls: vec![],
            line: Some(2),
            column: Some(1),
        })
        .unwrap();

    validator
        .handle(&XmlEvent::Text("35.0 135.0 0.0".into()))
        .unwrap();

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

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

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

    // Validation should pass
    assert!(validator.is_valid());
}

/// Test parsing PLATEAU building schema patterns
#[test]
fn test_plateau_building_pattern() {
    let building_xsd = 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/3.2"
               xmlns:bldg="http://www.opengis.net/citygml/building/2.0"
               targetNamespace="http://www.opengis.net/citygml/building/2.0"
               elementFormDefault="qualified">

        <xs:element name="Building" type="BuildingType"/>

        <xs:complexType name="BuildingType">
            <xs:sequence>
                <xs:element name="class" type="gml:CodeType" minOccurs="0"/>
                <xs:element name="function" type="gml:CodeType" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element name="usage" type="gml:CodeType" minOccurs="0" maxOccurs="unbounded"/>
                <xs:element name="yearOfConstruction" type="xs:gYear" minOccurs="0"/>
                <xs:element name="yearOfDemolition" type="xs:gYear" minOccurs="0"/>
                <xs:element name="roofType" type="gml:CodeType" minOccurs="0"/>
                <xs:element name="measuredHeight" type="gml:LengthType" minOccurs="0"/>
                <xs:element name="storeysAboveGround" type="xs:nonNegativeInteger" minOccurs="0"/>
                <xs:element name="storeysBelowGround" type="xs:nonNegativeInteger" minOccurs="0"/>
                <xs:element name="storeyHeightsAboveGround" type="gml:MeasureOrNullListType" minOccurs="0"/>
                <xs:element name="storeyHeightsBelowGround" type="gml:MeasureOrNullListType" minOccurs="0"/>
                <xs:element name="lod0FootPrint" type="gml:MultiSurfacePropertyType" minOccurs="0"/>
                <xs:element name="lod0RoofEdge" type="gml:MultiSurfacePropertyType" minOccurs="0"/>
                <xs:element name="lod1Solid" type="gml:SolidPropertyType" minOccurs="0"/>
                <xs:element name="lod2Solid" type="gml:SolidPropertyType" minOccurs="0"/>
            </xs:sequence>
        </xs:complexType>

    </xs:schema>"#;

    let schema = xsd::parse_xsd(building_xsd.as_bytes()).unwrap();

    // Check that Building element exists (now stored with namespace prefix)
    assert!(schema.elements.contains_key("bldg:Building"));

    // Check that BuildingType exists and has correct structure (now stored with namespace prefix)
    assert!(schema.types.contains_key("bldg:BuildingType"));

    if let Some(fastxml::schema::types::TypeDef::Complex(ct)) =
        schema.types.get("bldg:BuildingType")
    {
        // Check that it's a sequence with elements
        if let fastxml::schema::types::ContentModel::Sequence(elements) = &ct.content {
            // Find specific elements
            assert!(elements.iter().any(|e| e.name == "class"));
            assert!(elements.iter().any(|e| e.name == "measuredHeight"));
            assert!(elements.iter().any(|e| e.name == "storeysAboveGround"));

            // Check that optional elements have min_occurs = 0
            let class_elem = elements.iter().find(|e| e.name == "class").unwrap();
            assert_eq!(class_elem.min_occurs, 0);

            // Check unbounded elements
            let function_elem = elements.iter().find(|e| e.name == "function").unwrap();
            assert_eq!(function_elem.min_occurs, 0);
            assert_eq!(function_elem.max_occurs, None); // unbounded
        } else {
            panic!("Expected Sequence content model");
        }
    } else {
        panic!("Expected Complex type");
    }
}

/// Test parsing i-UR extension patterns used in PLATEAU
#[test]
fn test_plateau_iur_extension_pattern() {
    let uro_xsd = 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/3.2"
               xmlns:uro="https://www.geospatial.jp/iur/uro/3.2"
               targetNamespace="https://www.geospatial.jp/iur/uro/3.2"
               elementFormDefault="qualified">

        <xs:element name="buildingDetails" type="BuildingDetailsPropertyType"/>

        <xs:complexType name="BuildingDetailsPropertyType">
            <xs:sequence minOccurs="0">
                <xs:element ref="BuildingDetails"/>
            </xs:sequence>
        </xs:complexType>

        <xs:element name="BuildingDetails" type="BuildingDetailsType"/>

        <xs:complexType name="BuildingDetailsType">
            <xs:sequence>
                <xs:element name="serialNumberOfBuildingCertification" type="xs:string" minOccurs="0"/>
                <xs:element name="siteArea" type="gml:MeasureType" minOccurs="0"/>
                <xs:element name="totalFloorArea" type="gml:MeasureType" minOccurs="0"/>
                <xs:element name="buildingFootprintArea" type="gml:MeasureType" minOccurs="0"/>
                <xs:element name="buildingRoofEdgeArea" type="gml:MeasureType" minOccurs="0"/>
                <xs:element name="buildingStructureType" type="gml:CodeType" minOccurs="0"/>
                <xs:element name="fireproofStructureType" type="gml:CodeType" minOccurs="0"/>
            </xs:sequence>
        </xs:complexType>

        <xs:simpleType name="BuildingIDAttributeType">
            <xs:restriction base="xs:string">
                <xs:pattern value="[0-9]{13}"/>
            </xs:restriction>
        </xs:simpleType>

    </xs:schema>"#;

    let schema = xsd::parse_xsd(uro_xsd.as_bytes()).unwrap();

    // Check elements (now stored with namespace prefix)
    assert!(schema.elements.contains_key("uro:buildingDetails"));
    assert!(schema.elements.contains_key("uro:BuildingDetails"));

    // Check types (now stored with namespace prefix)
    assert!(schema.types.contains_key("uro:BuildingDetailsType"));
    assert!(schema.types.contains_key("uro:BuildingDetailsPropertyType"));
    assert!(schema.types.contains_key("uro:BuildingIDAttributeType"));

    // Check simple type restriction
    if let Some(fastxml::schema::types::TypeDef::Simple(st)) =
        schema.types.get("uro:BuildingIDAttributeType")
    {
        assert_eq!(st.base_type.as_deref(), Some("xs:string"));
        assert!(st.pattern.is_some());
        assert_eq!(st.pattern.as_deref(), Some("[0-9]{13}"));
    } else {
        panic!("Expected Simple type");
    }
}

/// Test that we can parse a GML file and use the streaming validator
#[test]
fn test_parse_real_gml_structure() {
    // A minimal valid CityGML structure
    let citygml = r#"<?xml version="1.0" encoding="UTF-8"?>
    <core:CityModel xmlns:core="http://www.opengis.net/citygml/2.0"
                    xmlns:gml="http://www.opengis.net/gml"
                    xmlns:dem="http://www.opengis.net/citygml/relief/2.0">
        <gml:boundedBy>
            <gml:Envelope srsName="http://www.opengis.net/def/crs/EPSG/0/6697" srsDimension="3">
                <gml:lowerCorner>35.0 135.0 0.0</gml:lowerCorner>
                <gml:upperCorner>36.0 136.0 100.0</gml:upperCorner>
            </gml:Envelope>
        </gml:boundedBy>
        <core:cityObjectMember>
            <dem:ReliefFeature gml:id="dem_test_001">
                <dem:lod>1</dem:lod>
            </dem:ReliefFeature>
        </core:cityObjectMember>
    </core:CityModel>"#;

    // Parse the document
    let doc = fastxml::parse(citygml).unwrap();
    let root = doc.get_root_element().unwrap();

    assert_eq!(root.get_name(), "CityModel");
    assert_eq!(root.get_prefix(), Some("core".into()));

    // Get child elements
    let children = root.get_child_elements();
    assert!(children.iter().any(|c| c.get_name() == "boundedBy"));
    assert!(children.iter().any(|c| c.get_name() == "cityObjectMember"));
}

/// Test that sequence maxOccurs is propagated to child elements
/// This reproduces a bug where GML's TrianglePatchArrayPropertyType
/// has <sequence maxOccurs="unbounded"> but the child Triangle element
/// was incorrectly compiled with max_occurs=1 instead of unbounded.
#[test]
fn test_sequence_maxoccurs_propagation() {
    // Pattern from GML: sequence has maxOccurs="unbounded", child element has no maxOccurs (defaults to 1)
    // Expected: child element should effectively be unbounded
    let xsd = r#"<?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
               targetNamespace="http://example.com/test"
               elementFormDefault="qualified">

        <xs:complexType name="ArrayPropertyType">
            <xs:sequence minOccurs="0" maxOccurs="unbounded">
                <xs:element name="item" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>

    </xs:schema>"#;

    let schema = xsd::parse_xsd(xsd.as_bytes()).unwrap();

    // Check that ArrayPropertyType exists
    assert!(schema.types.contains_key("ArrayPropertyType"));

    if let Some(fastxml::schema::types::TypeDef::Complex(ct)) =
        schema.types.get("ArrayPropertyType")
    {
        if let fastxml::schema::types::ContentModel::Sequence(elements) = &ct.content {
            let item = elements.iter().find(|e| e.name == "item").unwrap();
            // The sequence has maxOccurs="unbounded", so the child element should also be unbounded
            assert_eq!(
                item.max_occurs, None,
                "Child element in unbounded sequence should have max_occurs=None (unbounded), got {:?}",
                item.max_occurs
            );
            // The sequence has minOccurs="0", so the child element should be optional
            assert_eq!(
                item.min_occurs, 0,
                "Child element in optional sequence should have min_occurs=0, got {}",
                item.min_occurs
            );
        } else {
            panic!("Expected Sequence content model");
        }
    } else {
        panic!("Expected Complex type");
    }
}

/// Test that nested sequence maxOccurs is propagated correctly
#[test]
fn test_nested_sequence_maxoccurs_propagation() {
    let xsd = r#"<?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
               targetNamespace="http://example.com/test"
               elementFormDefault="qualified">

        <xs:complexType name="NestedArrayType">
            <xs:sequence maxOccurs="unbounded">
                <xs:sequence maxOccurs="3">
                    <xs:element name="inner" type="xs:string"/>
                </xs:sequence>
            </xs:sequence>
        </xs:complexType>

    </xs:schema>"#;

    let schema = xsd::parse_xsd(xsd.as_bytes()).unwrap();

    if let Some(fastxml::schema::types::TypeDef::Complex(ct)) = schema.types.get("NestedArrayType")
    {
        if let fastxml::schema::types::ContentModel::Sequence(elements) = &ct.content {
            let inner = elements.iter().find(|e| e.name == "inner").unwrap();
            // outer: unbounded * inner: 3 * element: 1 = unbounded
            assert_eq!(
                inner.max_occurs, None,
                "Nested sequence should propagate unbounded, got {:?}",
                inner.max_occurs
            );
        } else {
            panic!("Expected Sequence content model");
        }
    } else {
        panic!("Expected Complex type");
    }
}

/// Test that choice maxOccurs is propagated to child elements
#[test]
fn test_choice_maxoccurs_propagation() {
    let xsd = r#"<?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
               targetNamespace="http://example.com/test"
               elementFormDefault="qualified">

        <xs:complexType name="RepeatingChoiceType">
            <xs:choice maxOccurs="unbounded">
                <xs:element name="optionA" type="xs:string"/>
                <xs:element name="optionB" type="xs:integer"/>
            </xs:choice>
        </xs:complexType>

    </xs:schema>"#;

    let schema = xsd::parse_xsd(xsd.as_bytes()).unwrap();

    if let Some(fastxml::schema::types::TypeDef::Complex(ct)) =
        schema.types.get("RepeatingChoiceType")
    {
        if let fastxml::schema::types::ContentModel::Choice(elements) = &ct.content {
            let option_a = elements.iter().find(|e| e.name == "optionA").unwrap();
            // choice has maxOccurs="unbounded", so child elements should be unbounded
            assert_eq!(
                option_a.max_occurs, None,
                "Child element in unbounded choice should have max_occurs=None (unbounded), got {:?}",
                option_a.max_occurs
            );
        } else {
            panic!("Expected Choice content model");
        }
    } else {
        panic!("Expected Complex type");
    }
}

/// Test streaming parsing with validator
#[test]
fn test_streaming_parse_with_validator() {
    let citygml = r#"<?xml version="1.0" encoding="UTF-8"?>
    <gml:Envelope xmlns:gml="http://www.opengis.net/gml/3.2" srsName="EPSG:6697">
        <gml:lowerCorner>35.0 135.0</gml:lowerCorner>
        <gml:upperCorner>36.0 136.0</gml:upperCorner>
    </gml:Envelope>"#;

    // Parse the document
    let doc = fastxml::parse(citygml).unwrap();

    // Create schema with built-in types and use it for validation
    let schema = xsd::create_builtin_schema();
    let mut validator = OnePassSchemaValidator::new(Arc::new(schema));

    // Simulate validation by handling events
    validator
        .handle(&XmlEvent::StartElement {
            name: "Envelope".into(),
            prefix: Some("gml".into()),
            namespace: Some("http://www.opengis.net/gml/3.2".into()),
            attributes: vec![("srsName".into(), "EPSG:6697".into())],
            namespace_decls: vec![],
            line: Some(1),
            column: Some(1),
        })
        .unwrap();

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

    validator.finish().unwrap();

    // Validator should be valid
    assert!(validator.is_valid());

    // Verify we can parse the document
    let root = doc.get_root_element().unwrap();
    assert_eq!(root.get_name(), "Envelope");
}