fastxml 0.2.0

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
# fastxml

[![CI](https://github.com/reearth/fastxml/actions/workflows/ci.yml/badge.svg)](https://github.com/reearth/fastxml/actions/workflows/ci.yml)
[![Crates.io](https://img.shields.io/crates/v/fastxml.svg)](https://crates.io/crates/fastxml)
[![docs.rs](https://docs.rs/fastxml/badge.svg)](https://docs.rs/fastxml)
[![License](https://img.shields.io/crates/l/fastxml.svg)](LICENSE)

A fast, memory-efficient XML library for Rust with XPath and streaming schema validation support. Designed for processing large XML documents like CityGML files used in [PLATEAU](https://www.mlit.go.jp/plateau/).

## Features

- 🦀 **Pure Rust** — No C dependencies, no unsafe code
-**libxml Compatible** — Consistent parsing/XPath results
-**Streaming** — Parse and validate gigabyte-scale XML with ~1 MB memory footprint
- 🔄 **Zero-Copy Transform** — Stream-based XPath transformation with minimal allocations
- 📋 **Full XPath & XSD** — Complete XPath 1.0, schema parsing with import resolution, built-in GML types

## Performance

### Comparison with libxml

fastxml is designed as a drop-in replacement for libxml in Rust projects:

| Feature | libxml | fastxml |
|---------|--------|---------|
| DOM parsing |||
| XPath |||
| Schema validation | ✅ (DOM only) | ✅ (DOM + Streaming) |
| Streaming |||
| Memory efficiency | Low | High |
| Pure Rust |||

**Benchmark** (PLATEAU DEM GML, 907 MB, 31M nodes) — [benchmark code](examples/load_test_cli.rs):

Parse only:

| Mode | Time | Throughput | Memory |
|------|------|------------|--------|
| libxml DOM | 3.29s | 276 MB/s | 4.19 GB |
| fastxml DOM | 3.67s | 247 MB/s | 666 MB |
| fastxml Streaming | 3.13s | 290 MB/s | **~1 MB** |

Parse + Schema Validation (via xsi:schemaLocation):

| Mode | Time | Throughput | Memory |
|------|------|------------|--------|
| fastxml Streaming | 22.96s | 40 MB/s | **~1 MB** |

- **DOM**: fastxml uses **6.3x less memory** than libxml
- **Streaming**: Constant memory regardless of file size (only parser buffers)
- Schema validation auto-fetches XSD from `xsi:schemaLocation`

**Compatibility Testing**: Parsing, XPath, and validation results are verified against libxml2. Run with `cargo test --features compare-libxml` (requires libxml2-dev).

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
fastxml = "0.1"
```

### Features

By default, no HTTP client is included. Choose the features you need:

| Feature | Description |
|---------|-------------|
| `ureq` | Sync HTTP client (`UreqFetcher`) for schema fetching |
| `reqwest` | Async HTTP client (`ReqwestFetcher`) for schema fetching |
| `async-trait` | Async trait support for custom `AsyncSchemaStore` implementations |
| `profile` | Memory profiling utilities |
| `compare-libxml` | Enable libxml2 comparison tests (requires libxml2-dev) |

```toml
# For sync schema fetching
fastxml = { version = "0.1", features = ["ureq"] }

# For async schema fetching
fastxml = { version = "0.1", features = ["reqwest"] }

# For custom async implementations (without built-in HTTP client)
fastxml = { version = "0.1", features = ["async-trait"] }
```

## Quick Start

### DOM Parsing

```rust
use fastxml::{parse, evaluate};

let xml = r#"
<root>
    <item id="1">Hello</item>
    <item id="2">World</item>
</root>
"#;

// Parse XML
let doc = parse(xml.as_bytes())?;
println!("Node count: {}", doc.node_count());

// XPath query
let result = evaluate(&doc, "//item")?;
for node in result.into_nodes() {
    println!("Found: {}", node.tag_name());
}
```

### Streaming Parser

Process large files with minimal memory:

```rust
use fastxml::event::{StreamingParser, XmlEvent, XmlEventHandler};
use std::io::BufReader;
use std::fs::File;

struct MyHandler {
    element_count: usize,
}

impl XmlEventHandler for MyHandler {
    fn handle(&mut self, event: &XmlEvent) -> fastxml::error::Result<()> {
        if let XmlEvent::StartElement { name, .. } = event {
            self.element_count += 1;
            println!("Element: {}", name);
        }
        Ok(())
    }
}

let file = File::open("large_file.xml")?;
let reader = BufReader::new(file);

let mut parser = StreamingParser::new(reader);
parser.add_handler(Box::new(MyHandler { element_count: 0 }));
parser.parse()?;
```

### Streaming Transform

Transform XML documents efficiently with XPath-based element selection. Only matched elements are converted to DOM, providing significant memory savings for large files.

```rust
use fastxml::transform::StreamTransformer;

let xml = r#"<root><item id="1">A</item><item id="2">B</item></root>"#;

// Modify specific elements
let result = StreamTransformer::new(xml)
    .xpath("//item[@id='2']")
    .transform(|node| {
        node.set_attribute("modified", "true");
    })
    .to_string()
    .unwrap();
// Result: <root><item id="1">A</item><item id="2" modified="true">B</item></root>

// Remove elements
let result = StreamTransformer::new(xml)
    .xpath("//item[@id='1']")
    .transform(|node| {
        node.remove();
    })
    .to_string()
    .unwrap();
// Result: <root><item id="2">B</item></root>

// Extract data without transformation
let ids: Vec<String> = StreamTransformer::new(xml)
    .xpath("//item")
    .collect(|node| node.get_attribute("id").unwrap_or_default())
    .unwrap();
// ids: ["1", "2"]

// Iterate over matched elements
let mut count = 0;
StreamTransformer::new(xml)
    .xpath("//item")
    .for_each(|node| {
        println!("Found: {:?}", node.get_content());
        count += 1;
    })
    .unwrap();
```

With namespace support:

```rust
use fastxml::{parse, transform::StreamTransformer};

let xml = r#"<root xmlns:gml="http://www.opengis.net/gml">
    <gml:Point><gml:pos>1 2</gml:pos></gml:Point>
</root>"#;

// Option 1: Register namespaces manually
let result = StreamTransformer::new(xml)
    .namespaces([
        ("gml", "http://www.opengis.net/gml"),
        ("bldg", "http://www.opengis.net/citygml/building/2.0"),
    ])
    .xpath("//gml:Point")
    .transform(|node| {
        node.set_attribute("srsName", "EPSG:4326");
    })
    .to_string()
    .unwrap();

// Option 2: Import namespaces from parsed document
let doc = parse(xml).unwrap();
let result = StreamTransformer::new(xml)
    .with_document_namespaces(&doc)
    .xpath("//gml:Point")
    .transform(|node| {
        node.set_attribute("srsName", "EPSG:4326");
    })
    .to_string()
    .unwrap();
```

**Performance** (100K elements, 11 MB XML):

| Approach | Time | Memory |
|----------|------|--------|
| Streaming Transform | 47ms | ~11 MB |
| DOM Parse + XPath | 141ms | ~135 MB |

Streaming is **3x faster** and uses **12x less memory**.

### Schema Validation

Validate XML documents against XSD schemas:

```rust
use fastxml::{parse, validate_document_by_schema};

// Parse the XML document
let xml = std::fs::read("document.xml")?;
let doc = parse(&xml)?;

// Validate against XSD schema (fetches imports automatically)
let errors = validate_document_by_schema(&doc, "schema.xsd".to_string())?;

if errors.is_empty() {
    println!("Document is valid!");
} else {
    for error in &errors {
        println!("{}", error);
    }
}
```

#### Auto-detect Schema from xsi:schemaLocation

Automatically fetch and validate against schemas referenced in the XML document:

```rust
use fastxml::{parse, validate_with_schema_location};

let xml = r#"<?xml version="1.0"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://example.com/ns http://example.com/schema.xsd">
    <element>content</element>
</root>"#;

let doc = parse(xml.as_bytes())?;

// Reads xsi:schemaLocation, fetches schemas, and validates
let errors = validate_with_schema_location(&doc)?;
```

This requires the `ureq` feature:

```toml
fastxml = { version = "0.1", features = ["ureq"] }
```

### Streaming Validation

For large files, validate while parsing in a single pass:

```rust
use fastxml::event::StreamingParser;
use fastxml::schema::validator::StreamingSchemaValidator;
use fastxml::schema::parse_xsd;
use std::sync::Arc;
use std::io::BufReader;
use std::fs::File;

// Load and compile the schema
let xsd_content = std::fs::read("schema.xsd")?;
let schema = Arc::new(parse_xsd(&xsd_content)?);

// Create streaming parser with validation
let file = File::open("large_document.xml")?;
let mut parser = StreamingParser::new(BufReader::new(file));

let validator = StreamingSchemaValidator::new(Arc::clone(&schema));
parser.add_handler(Box::new(validator));

// Parse and validate in single pass
parser.parse()?;
```

#### Streaming Validation with xsi:schemaLocation

For files with `xsi:schemaLocation`, fetch schemas automatically and validate in streaming mode with a single pass:

```rust
use fastxml::streaming_validate_with_schema_location;
use std::fs::File;
use std::io::BufReader;

let file = File::open("large_document.xml")?;

// Single-pass: reads schemaLocation from first element, fetches schema, validates
let errors = streaming_validate_with_schema_location(BufReader::new(file))?;
```

Or with more control using `LazySchemaValidator`:

```rust
use fastxml::event::StreamingParser;
use fastxml::schema::{LazySchemaValidator, UreqFetcher};
use std::fs::File;
use std::io::BufReader;

let file = File::open("document.xml")?;
let mut parser = StreamingParser::new(BufReader::new(file));

// LazySchemaValidator fetches schema on first StartElement
let validator = LazySchemaValidator::new(UreqFetcher::new());
parser.add_handler(Box::new(validator));
parser.parse()?;
```

This requires the `ureq` feature.

### Error Handling

Validation errors include detailed location and context information:

```rust
use fastxml::{parse, validate_document_by_schema, ErrorLevel};

let doc = parse(xml_bytes)?;
let errors = validate_document_by_schema(&doc, schema_path)?;

for error in &errors {
    // Error severity: Warning, Error, or Fatal
    match error.level {
        ErrorLevel::Warning => print!("[WARN] "),
        ErrorLevel::Error => print!("[ERROR] "),
        ErrorLevel::Fatal => print!("[FATAL] "),
    }

    // Location information
    if let Some(path) = &error.element_path {
        print!("{}", path);
    }
    if let Some(line) = error.line {
        print!(" (line {})", line);
    }
    print!(": ");

    // Error message with expected/found values
    println!("{}", error.message);
    if let (Some(expected), Some(found)) = (&error.expected, &error.found) {
        println!("  expected: {}, found: {}", expected, found);
    }
}

// Filter by severity
let fatal_errors: Vec<_> = errors.iter()
    .filter(|e| e.level == ErrorLevel::Fatal)
    .collect();
```

### XPath with Namespaces

```rust
use fastxml::{parse, evaluate};

let xml = r#"
<core:CityModel xmlns:core="http://www.opengis.net/citygml/2.0"
                xmlns:bldg="http://www.opengis.net/citygml/building/2.0">
    <bldg:Building gml:id="bldg_001">
        <bldg:measuredHeight>25.5</bldg:measuredHeight>
    </bldg:Building>
</core:CityModel>
"#;

let doc = parse(xml.as_bytes())?;

// Query with namespace prefix
let buildings = evaluate(&doc, "//bldg:Building")?;
println!("Found {} buildings", buildings.into_nodes().len());

// Query with name() function
let heights = evaluate(&doc, "//*[name()='measuredHeight']/text()")?;
```

## Limitations

### XPath

**Supported expressions:**

| Expression | Example | Description |
|------------|---------|-------------|
| Absolute path | `/root/child` | Direct path from root |
| Descendant | `//element` | Any descendant |
| Wildcard | `//*` | All elements |
| Name predicate | `//*[name()='Building']` | Match by name |
| Logical operators | `//*[name()='A' or name()='B']` | `and`, `or`, `not` |
| Text | `//element/text()` | Text content |
| Namespace | `//bldg:Building` | Namespaced elements |
| Axes | `ancestor::div`, `following-sibling::*` | All standard axes |
| Arithmetic | `@value + 10` | `+`, `-`, `*`, `div`, `mod` |
| Comparison | `@count > 5` | `=`, `!=`, `<`, `>`, `<=`, `>=` |
| Functions | `count(//item)`, `contains(@name, 'test')` | Position, string, math functions |
| Union | `//a \| //b` | Combine multiple paths |
| Variables | `//item[@id=$target]` | Variable references |
| Namespace axis | `namespace::*` | In-scope namespaces |

### XSD Schema

**Supported:** Element/attribute definitions, complex types (sequence/choice/all), simple types (restriction/list/union), type inheritance, facets, attribute/model groups, import/include/redefine, built-in XSD and GML types, identity constraints (unique/key/keyref), streaming validation with error location info.

**Partial:** Substitution groups (parsing only).

### Not Supported

- XQuery, DTD validation, XSLT, XInclude, XML Signature/Encryption
- Catalog support
- Entity expansion (basic only)

## Development

```bash
cargo test                              # Run all tests
cargo test --features compare-libxml    # With libxml comparison (requires libxml2-dev)
cargo bench                             # Run benchmarks
```

### Load Test CLI

```bash
# Synthetic data
cargo run --release --example load_test_cli -- --pattern citygml --size 50000

# Real files
cargo run --release --example load_test_cli -- ./file.xml

# Real files with schema validation (auto-fetches from xsi:schemaLocation)
cargo run --release --features ureq --example load_test_cli -- ./file.xml --validate

# Compare with libxml
cargo run --release --features compare-libxml --example load_test_cli -- --mode dom ./file.xml
```

| Option | Description |
|--------|-------------|
| `--pattern <PATTERN>` | `many-elements`, `deep-nesting`, `large-content`, `citygml` |
| `--size <SIZE>` | Size for pattern |
| `--mode <MODE>` | `dom`, `streaming`, or `both` (default) |
| `--validate` | Enable schema validation (reads `xsi:schemaLocation` and fetches schemas, requires `ureq` feature) |

## License

MIT OR Apache-2.0