Skip to main content

Crate fastxml

Crate fastxml 

Source
Expand description

fastxml - Fast, memory-efficient XML library with XPath and XSD validation support.

This library provides XML parsing, XPath evaluation, and XSD schema validation with a focus on memory efficiency through streaming processing.

§Features

  • Fast XML Parsing: Built on quick-xml for high-performance parsing
  • XPath Support: Evaluate XPath 1.0 expressions
  • XSD Validation: Stream-based schema validation
  • Memory Efficient: Streaming APIs to minimize memory usage
  • Thread Safe: Safe concurrent access through careful design
  • Async Support: Async schema fetching and resolution with tokio

§Feature Flags

  • ureq: Enables synchronous HTTP client for schema fetching (recommended)
  • tokio: Enables async HTTP client and schema resolution with reqwest
  • async-trait: Enables async trait support for custom implementations
  • profile: Enables memory profiling utilities

§Quick Start

use fastxml::{parse, xpath, get_root_node, get_node_tag};

// Parse XML
let xml = r#"<root xmlns:gml="http://www.opengis.net/gml">
    <gml:name>Hello World</gml:name>
</root>"#;

let doc = parse(xml).unwrap();

// Get root element
let root = get_root_node(&doc).unwrap();
println!("Root element: {}", get_node_tag(&root));

// Evaluate XPath
let result = xpath::evaluate(&doc, "//gml:name").unwrap();
let texts = xpath::collect_text_values(&result);
println!("Found: {:?}", texts);

§libxml API Compatibility

This library provides API compatibility with the libxml crate for easier migration:

use fastxml::{
    // Types
    XmlDocument, XmlNode, XmlRoNode, XmlContext,
    // Parsing
    parse,
    // XPath
    evaluate, create_context, find_nodes_by_xpath,
    collect_text_values, collect_text_value,
    // Node operations
    get_root_node, get_root_readonly_node, get_node_tag,
    node_to_xml_string, readonly_node_to_xml_string,
    // Schema validation
    create_xml_schema_validation_context,
    validate_document_by_schema,
    parse_schema_locations,
};

§Streaming Processing

For large files, use streaming APIs to minimize memory usage:

use fastxml::event::{StreamingParser, XmlEventHandler, XmlEvent};
use fastxml::error::Result;

struct MyHandler;

impl XmlEventHandler for MyHandler {
    fn handle(&mut self, event: &XmlEvent) -> Result<()> {
        match event {
            XmlEvent::StartElement { name, .. } => {
                println!("Start: {}", name);
            }
            _ => {}
        }
        Ok(())
    }

    fn as_any(self: Box<Self>) -> Box<dyn std::any::Any> {
        self
    }
}

let xml = "<root><child/></root>";
let mut parser = StreamingParser::new(xml.as_bytes());
parser.add_handler(Box::new(MyHandler));
parser.parse().unwrap();

§Async Schema Resolution

Parse XSD schemas with async import/include resolution (requires tokio feature):

use fastxml::schema::{
    AsyncDefaultFetcher,
    parse_xsd_with_imports_async,
};

#[tokio::main]
async fn main() -> fastxml::error::Result<()> {
    let xsd_content = std::fs::read("schema.xsd")?;
    let fetcher = AsyncDefaultFetcher::new()?;

    let schema = parse_xsd_with_imports_async(
        &xsd_content,
        "http://example.com/schema.xsd",
        &fetcher,
    ).await?;

    Ok(())
}

Re-exports§

pub use error::Error;
pub use error::ErrorLevel;
pub use error::ErrorLocation;
pub use error::Result;
pub use error::StructuredError;
pub use error::ValidationErrorType;
pub use document::DocumentBuilder;
pub use document::XmlDocument;
pub use node::NodeId;
pub use node::NodeType;
pub use node::XmlNode;
pub use node::XmlRoNode;
pub use namespace::Namespace;
pub use namespace::NamespaceResolver;
pub use parser::ParserOptions;
pub use parser::parse;
pub use parser::parse_from_bufread;
pub use parser::parse_schema_locations;
pub use parser::parse_with_options;
pub use position::PositionTrackingReader;
pub use xpath::context::XmlContext;
pub use xpath::context::XmlSafeContext;

Modules§

document
XML document representation.
error
Error types for fastxml.
event
SAX-like event streaming for XML processing.
generator
XML stream generator for load testing.
namespace
Namespace handling for XML documents.
node
XML node representation and operations.
parser
XML parsing with quick-xml backend.
position
Position tracking reader for accurate line/column reporting.
profile
Profiling utilities for memory and performance measurement.
schema
XSD schema handling and validation.
serialize
XML serialization (node to string).
transform
Streaming XML transformation with zero-copy output.
xpath
XPath expression support.

Structs§

CompactString
A CompactString is a compact string type that can be used almost anywhere a String or str can be used.

Functions§

collect_text_value
Collects a single text value from an XPath result.
collect_text_values
Collects text values from an XPath result.
create_context
Creates an XPath context for a document.
create_safe_context
Creates a thread-safe XPath context for a document.
create_xml_schema_validation_context
Creates an XSD schema validation context.
create_xml_schema_validation_context_from_buffer
Creates an XSD schema validation context from a buffer.
evaluate
Evaluates an XPath expression on a document.
find_nodes_by_xpath
Finds nodes by XPath expression relative to a node.
find_readonly_nodes_by_xpath
Finds read-only nodes by XPath expression.
find_readonly_nodes_in_elements
Finds read-only nodes matching element names.
find_safe_readonly_nodes_by_xpath
Finds read-only nodes using a thread-safe context.
get_node_prefix
Gets the namespace prefix of a node.
get_node_tag
Gets the qualified tag name of a node (prefix:name or just name).
get_readonly_node_prefix
Gets the namespace prefix of a read-only node.
get_readonly_node_tag
Gets the qualified tag name of a read-only node.
get_root_node
Gets the root element node from a document.
get_root_readonly_node
Gets the root element as a read-only node.
get_schema_from_schema_location_with_fetcher
Gets a compiled schema from xsi:schemaLocation with a custom fetcher.
node_to_xml_string
Serializes a node to an XML string.
parse_xsd
Parses XSD content and returns a compiled schema.
parse_xsd_with_imports
Parses XSD content with import resolution.
parse_xsd_with_imports_multiple
Parses multiple XSD entry schemas with shared import/include resolution.
readonly_node_to_xml_string
Serializes a read-only node to an XML string.
streaming_validate_with_schema_location_and_fetcher
Validates XML from a reader using streaming parser with a custom fetcher.
validate_document_by_schema
Validates a document against an XSD schema.
validate_document_by_schema_context
Validates a document using an existing validation context.
validate_with_schema_location_and_fetcher
Validates a document using schemas referenced in xsi:schemaLocation with a custom fetcher.