### Run quick-xml Examples Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/README.md Examples are included in the repository. Run them using `cargo run --example `. ```bash cargo run --example [--features ...] ``` -------------------------------- ### Basic XML Writing Example Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/writer.md Demonstrates how to create a Writer, write start, text, and end events for a root element, and retrieve the resulting XML string. Ensure the necessary event types are imported. ```rust use quick_xml::events::{Event, BytesStart, BytesEnd, BytesText}; use quick_xml::writer::Writer; use std::io::Cursor; let mut writer = Writer::new(Cursor::new(Vec::new())); // Write Start event let start = BytesStart::new("root"); writer.write_event(Event::Start(start)).unwrap(); // Write Text event let text = BytesText::new("hello"); writer.write_event(Event::Text(text)).unwrap(); // Write End event let end = BytesEnd::new("root"); writer.write_event(Event::End(end)).unwrap(); let result = writer.into_inner().into_inner(); assert_eq!(result, b"hello"); ``` -------------------------------- ### Complete Event Flow Example Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/events.md Demonstrates a complete event loop for parsing XML using Quick-XML's Reader. This example shows how to handle various event types like declarations, start/end tags, text content, and end-of-file. ```rust use quick_xml::events::Event; use quick_xml::reader::Reader; let xml = r#" text "#; let mut reader = Reader::from_str(xml); let mut buf = Vec::new(); loop { buf.clear(); match reader.read_event_into(&mut buf) { Ok(Event::Decl(_)) => println!("XML declaration"), Ok(Event::Start(e)) => println!("Start: {:?}", e.name()), Ok(Event::Text(e)) => println!("Text: {}", e.decode().unwrap()), Ok(Event::End(e)) => println!("End: {:?}", e.name()), Ok(Event::Eof) => break, Ok(_) => {}, Err(e) => eprintln!("Error: {}", e), } } ``` -------------------------------- ### Example: Using BytesStart Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/events.md Demonstrates how to use BytesStart to create and write an XML element with attributes. ```APIDOC #### Example: Using BytesStart ```rust use quick_xml::events::{BytesStart, Event}; use quick_xml::writer::Writer; use std::io::Cursor; let mut writer = Writer::new(Cursor::new(Vec::new())); let mut start = BytesStart::new("element"); start.push_attribute(("id", "1")); start.push_attribute(("class", "active")); writer.write_event(Event::Start(start.borrow())).unwrap(); writer.write_event(Event::End(start.to_end())).unwrap(); // Output: ``` ``` -------------------------------- ### Basic Writing Example Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/writer.md An example demonstrating basic XML writing using the Writer API. ```APIDOC ## Example: Basic Writing ```rust use quick_xml::events::{Event, BytesStart, BytesEnd, BytesText}; use quick_xml::writer::Writer; use std::io::Cursor; let mut writer = Writer::new(Cursor::new(Vec::new())); // Write Start event let start = BytesStart::new("root"); writer.write_event(Event::Start(start)).unwrap(); // Write Text event let text = BytesText::new("hello"); writer.write_event(Event::Text(text)).unwrap(); // Write End event let end = BytesEnd::new("root"); writer.write_event(Event::End(end)).unwrap(); let result = writer.into_inner().into_inner(); assert_eq!(result, b"hello"); ``` ``` -------------------------------- ### Iterating Attributes Example Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/events.md An example demonstrating how to iterate over attributes of a `BytesStart` element. ```APIDOC #### Example: Iterating Attributes ```rust use quick_xml::events::BytesStart; let start = BytesStart::new("element"); let start = start.with_attributes(vec![("id", "1"), ("class", "active")]); for attr in start.attributes() { let attr = attr.unwrap(); println!("{} = {:?}", String::from_utf8_lossy(attr.key.as_ref()), attr.value); } ``` ``` -------------------------------- ### Configuration Example Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/reader.md Illustrates how to modify reader configuration, specifically for text trimming. ```APIDOC #### Example: Configuration ```rust use quick_xml::reader::Reader; let xml = r" text "; let mut reader = Reader::from_str(xml); reader.config_mut().trim_text(true); // Text event will not contain leading/trailing whitespace ``` ``` -------------------------------- ### Serde Compatibility Example Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/features_and_config.md Demonstrates how to derive `Serialize` and `Deserialize` for a struct to enable compatibility with the serde ecosystem for XML data. ```rust #[derive(serde::Serialize, serde::Deserialize)] struct Root { #[serde(rename = "@id")] id: u32, } // Can be serialized to JSON, TOML, etc. after being deserialized from XML ``` -------------------------------- ### Example: Using BinaryStream to Read Binary Data Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/reader.md Demonstrates how to use `BinaryStream` to read raw binary data from an XML source after parsing an event. ```rust use std::io::Read; use quick_xml::reader::Reader; let xml = r#"binary data"#; let mut reader = Reader::from_str(xml); // Read Start event reader.read_event().unwrap(); // Use stream to read binary data let mut binary_data = [0u8; 11]; reader.stream().read_exact(&mut binary_data).unwrap(); // Read End event reader.read_event().unwrap(); ``` -------------------------------- ### Multi-Namespace Document Example Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/namespace_reader.md A complete example demonstrating how to use NsReader to parse an XML document with multiple namespaces and extract information from namespaced elements. ```APIDOC ## Complete Example: Multi-Namespace Document ```rust use quick_xml::events::Event; use quick_xml::name::ResolveResult::*; use quick_xml::reader::NsReader; let xml = r###" Article "###; let mut reader = NsReader::from_str(xml); let mut buf = Vec::new(); loop { buf.clear(); match reader.read_resolved_event_into(&mut buf) { Ok((ns, Event::Start(e))) => { if ns.as_ref() == b"http://purl.org/rss/1.0/modules/content/" { println!("Found content:encoded element"); } else if ns.as_ref() == b"http://www.w3.org/2005/Atom" { println!("Found Atom element: {}", String::from_utf8_lossy(e.local_name().as_ref())); } } Ok((_, Event::Eof)) => break, Ok(_) => {} // Ignore other events Err(e) => eprintln!("Error: {}", e), } } ``` ``` -------------------------------- ### Basic Reading Example Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/reader.md Demonstrates how to use the Reader to parse an XML string and process events. ```APIDOC ## Example: Basic Reading ```rust use quick_xml::events::Event; use quick_xml::reader::Reader; let xml = r"text"; let mut reader = Reader::from_str(xml); let mut buf = Vec::new(); loop { buf.clear(); match reader.read_event_into(&mut buf) { Ok(Event::Start(e)) => println!("Start tag: {}", String::from_utf8_lossy(e.name().as_ref())), Ok(Event::End(e)) => println!("End tag: {}", String::from_utf8_lossy(e.name().as_ref())), Ok(Event::Text(e)) => println!("Text: {}", e.decode().unwrap()), Ok(Event::Eof) => break, Ok(_) => {{}}, Err(e) => eprintln!("Error: {}", e), } } ``` ``` -------------------------------- ### Example: Handling CDATA Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/events.md Demonstrates how to use BytesCData::escaped to handle CDATA content and BytesCData::new for creating CDATA. ```APIDOC ## Example: Handling CDATA ### Description This example shows how to create CDATA sections, including handling content that requires splitting due to `]]>` sequences, and creating CDATA for writing. ### Code ```rust use quick_xml::events::BytesCData; // CDATA with content that needs splitting let content = "foo]]>bar"; let parts: Vec<_> = BytesCData::escaped(content).collect(); assert_eq!(parts.len(), 2); // Create CDATA for writing let cdata = BytesCData::new("raw content without escapes"); ``` ``` -------------------------------- ### Example: Unknown Version Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/errors.md Demonstrates an XML declaration with an unsupported version attribute. Use 'version="1.0"' or 'version="1.1"' for compatibility. ```xml ``` -------------------------------- ### Writing XML with quick-xml Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/00_START_HERE.md Shows how to write XML events using `quick_xml::writer::Writer`. This example uses `std::io::Cursor` to write to a `Vec`. ```rust use quick_xml::writer::Writer; use quick_xml::events::{BytesStart, BytesEnd, BytesText, Event}; use std::io::Cursor; let mut writer = Writer::new(Cursor::new(Vec::new())); writer.write_event(Event::Start(BytesStart::new("root")))?; writer.write_event(Event::Text(BytesText::new("content")))?; writer.write_event(Event::End(BytesEnd::new("root")))?; let result = writer.into_inner().into_inner(); // result now contains: b"content" ``` -------------------------------- ### Adding quick-xml Dependency with Features Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/00_START_HERE.md Example TOML snippet for adding quick-xml to a project's dependencies, including optional features like 'serialize' and 'encoding'. ```toml [dependencies] quick-xml = { version = "0.40", features = ["serialize", "encoding"] } ``` -------------------------------- ### Formatted XML Output Example Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/writer.md Demonstrates writing events to a Writer configured for indentation. The output will be automatically formatted with the specified indentation. ```rust use quick_xml::events::{Event, BytesStart, BytesEnd, BytesText}; use quick_xml::writer::Writer; use std::io::Cursor; let mut writer = Writer::new_with_indent(Cursor::new(Vec::new()), b' ', 2); let root = BytesStart::new("root"); writer.write_event(Event::Start(root)).unwrap(); let child = BytesStart::new("child"); writer.write_event(Event::Start(child)).unwrap(); let text = BytesText::new("content"); writer.write_event(Event::Text(text)).unwrap(); writer.write_event(Event::End(BytesEnd::new("child"))).unwrap(); writer.write_event(Event::End(BytesEnd::new("root"))).unwrap(); let result = String::from_utf8(writer.into_inner().into_inner()).unwrap(); // Output has automatic indentation ``` -------------------------------- ### Basic Deserialization Example Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/serialization.md Demonstrates how to deserialize an XML string into a Rust struct using `quick_xml::de::Deserializer`. Ensure the target struct implements `Deserialize`. ```rust use quick_xml::de::Deserializer; let xml = r###"content"###; let mut de = Deserializer::from_str(xml); let root: Root = Root::deserialize(&mut de).unwrap(); ``` -------------------------------- ### Adding Attributes with BytesStart::push_attribute() Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/INDEX.md Shows how to add attributes to an XML start element using `BytesStart::push_attribute()`. This is essential for creating elements with specific properties. ```rust let mut element = BytesStart::new("element"); element.push_attribute("key", "value"); ``` -------------------------------- ### Enable Quick-xml Cargo Features Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/features_and_config.md Specify desired features in your Cargo.toml file to customize quick-xml's functionality. This example enables serialization, encoding, and async-tokio support. ```toml [dependencies] quick-xml = { version = "0.40", features = ["serialize", "encoding", "async-tokio"] } ``` -------------------------------- ### Example: Missing Decl Version (Some) Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/errors.md Shows an XML declaration where the first attribute is not 'version'. Reorder attributes so 'version' appears first. ```xml ``` -------------------------------- ### Example: Missing Doctype Name Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/errors.md An example of a DOCTYPE declaration lacking a root element name. Provide the root element name, e.g., ''. ```xml ``` -------------------------------- ### Serde Integration Note Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/writer.md Illustrates the setup for Serde integration with `Writer` when the `serialize` feature is enabled. Note that `Writer` operates on low-level events, and `se::to_string` is recommended for direct serialization. ```rust use quick_xml::de::to_string; use quick_xml::se::to_string; use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize)] struct Root { #[serde(rename = "@version")] version: String, #[serde(rename = "$text")] content: String, } let root = Root { version: "1.0".to_string(), content: "hello".to_string(), }; // Note: Writer works with low-level events; use se::to_string for direct serialization ``` -------------------------------- ### Reading XML Events Source: https://github.com/tafia/quick-xml/blob/master/README.md Demonstrates how to read XML events using quick-xml's Reader. It shows how to process start tags, text content, and handle end-of-file events. The reader is configured to trim text content. ```Rust use quick_xml::events::Event; use quick_xml::reader::Reader; let xml = r#" Test Test 2 "#; let mut reader = Reader::from_str(xml); reader.config_mut().trim_text(true); let mut count = 0; let mut txt = Vec::new(); let mut buf = Vec::new(); // The `Reader` does not implement `Iterator` because it outputs borrowed data (`Cow`s) loop { // NOTE: this is the generic case when we don't know about the input BufRead. // when the input is a &str or a &[u8], we don't actually need to use another // buffer, we could directly call `reader.read_event()` match reader.read_event_into(&mut buf) { Err(e) => panic!("Error at position {}: {:?}", reader.error_position(), e), // exits the loop when reaching end of file Ok(Event::Eof) => break, Ok(Event::Start(e)) => { match e.name().as_ref() { b"tag1" => println!("attributes values: {:?}", e.attributes().map(|a| a.unwrap().value) .collect::>()), b"tag2" => count += 1, _ => () } } Ok(Event::Text(e)) => txt.push(e.decode().unwrap().into_owned()), // There are several other `Event`s we do not consider here _ => () } // if we don't keep a borrow elsewhere, we can clear the buffer to keep memory usage low buf.clear(); } ``` -------------------------------- ### Example: Missing Decl Version (None) Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/errors.md Illustrates an XML declaration missing the 'version' attribute. Ensure 'version="1.0"' is the first attribute for correct parsing. ```xml ``` -------------------------------- ### Example: Reporting XML Parsing Errors Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/errors.md Demonstrates how to use `error_position()` and `buffer_position()` to report the location of parsing errors in an XML string. ```rust use quick_xml::reader::Reader; let xml = rLone break, Err(e) => { eprintln!("Error at byte {}: {}", reader.error_position(), e); // error_position() = 6 (start of {} } } ``` -------------------------------- ### Namespace Resolution Example Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/namespace_reader.md Demonstrates how to use NsReader and its resolver to determine the namespace URI and local name for XML elements based on their qualified names and xmlns declarations. ```rust use quick_xml::reader::NsReader; use quick_xml::name::QName; let xml = r###" "###; let mut reader = NsReader::from_str(xml); let mut buf = Vec::new(); reader.read_event_into(&mut buf).unwrap(); // Start root reader.read_event_into(&mut buf).unwrap(); // Start unqualified let (ns1, local1) = reader.resolver().resolve_element(QName(b"unqualified")); // ns1 is Bound to "http://default.ns" (from default xmlns) reader.read_event_into(&mut buf).unwrap(); // End unqualified reader.read_event_into(&mut buf).unwrap(); // Start p:qualified let (ns2, local2) = reader.resolver().resolve_element(QName(b"p:qualified")); // ns2 is Bound to "http://prefix.ns" (from xmlns:p) ``` -------------------------------- ### Create XML Element with Attributes and Text Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/writer.md Demonstrates creating a root element with an attribute and a child element with its own attribute and text content. Ensure the writer is properly initialized and unwrapped to get the final XML string. ```rust use quick_xml::writer::Writer; use std::io::Cursor; let mut writer = Writer::new(Cursor::new(Vec::new())); writer.create_element("root") .with_attribute(("version", "1.0")) .write_inner_content(|writer| { writer.create_element("child") .with_attribute(("id", "1")) .write_text_contents("text") }) .unwrap(); let result = writer.into_inner().into_inner(); // Output: text ``` -------------------------------- ### Basic XML Reading Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/reader.md Demonstrates how to use the Reader to parse an XML string and process events like start tags, end tags, and text content. It handles the End-Of-File event to break the loop. ```rust use quick_xml::events::Event; use quick_xml::reader::Reader; let xml = r"text"; let mut reader = Reader::from_str(xml); let mut buf = Vec::new(); loop { buf.clear(); match reader.read_event_into(&mut buf) { Ok(Event::Start(e)) => println!("Start tag: {}", String::from_utf8_lossy(e.name().as_ref())), Ok(Event::End(e)) => println!("End tag: {}", String::from_utf8_lossy(e.name().as_ref())), Ok(Event::Text(e)) => println!("Text: {}", e.decode().unwrap()), Ok(Event::Eof) => break, Ok(_) => {}, Err(e) => eprintln!("Error: {}", e), } } ``` -------------------------------- ### Run XML parser benchmarks Source: https://github.com/tafia/quick-xml/blob/master/compare/README.md Execute these commands from the quick-xml root directory to run the benchmark suite. ```bash cd compare cargo bench ``` -------------------------------- ### Run quick-xml Benchmarks Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/README.md Benchmarks for the quick-xml crate can be executed using the `cargo bench` command. ```bash cargo bench --benches ``` -------------------------------- ### BytesStart Construction Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/events.md Methods for creating new BytesStart instances. ```APIDOC ## BytesStart Construction ### `new` Creates a new `BytesStart` from a tag name. #### Signature `fn new>>(name: C) -> Self` ### `from_content` Creates from complete content (name + attributes) with explicit name boundary. #### Signature `fn from_content>>(content: C, name_len: usize) -> Self` ``` -------------------------------- ### Decoder::utf8 Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/types.md Provides a constant function to get a UTF-8 decoder. ```APIDOC ## Decoder::utf8 ### Returns a decoder for UTF-8 encoding. ### Method `Decoder::utf8()` ### Response #### Success Response (Self) - **Self** - A `Decoder` instance configured for UTF-8. ``` -------------------------------- ### Run quick-xml Tests Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/README.md The test suite can be run with various feature flags. Use `--all-features` for all tests, or specify individual features. ```bash # All tests with all features cargo test --all-features ``` ```bash # Specific feature cargo test --features serialize ``` ```bash # No features (minimal) cargo test ``` -------------------------------- ### Construct and Write BytesStart Event Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/events.md Demonstrates how to create a BytesStart event, add attributes to it, and then write it to an XML output using a Writer. This is useful for programmatically generating XML structures. ```rust use quick_xml::events::{BytesStart, Event}; use quick_xml::writer::Writer; use std::io::Cursor; let mut writer = Writer::new(Cursor::new(Vec::new())); let mut start = BytesStart::new("element"); start.push_attribute(("id", "1")); start.push_attribute(("class", "active")); writer.write_event(Event::Start(start.borrow())).unwrap(); writer.write_event(Event::End(start.to_end())).unwrap(); // Output: ``` -------------------------------- ### Reading XML with quick-xml Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/00_START_HERE.md Demonstrates how to read XML events using `quick_xml::reader::Reader`. Ensure to handle `Event::Start`, `Event::Text`, and `Event::Eof`. ```rust use quick_xml::reader::Reader; use quick_xml::events::Event; let xml = r###"text"###; let mut reader = Reader::from_str(xml); let mut buf = Vec::new(); loop { buf.clear(); match reader.read_event_into(&mut buf) { Ok(Event::Start(e)) => println!("Tag: {:?}", e.name()), Ok(Event::Text(e)) => println!("Text: {}", e.decode().unwrap()), Ok(Event::Eof) => break, Ok(_) => {}, Err(e) => panic!("Error: {}", e), } } ``` -------------------------------- ### Attributes Iterator Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/events.md Provides an iterator over tag attributes. It includes methods to get the next attribute and to enable/disable validation checks. ```APIDOC ## Attributes Iterator over tag attributes. ```rust pub struct Attributes<'a> { // ... } ``` | Method | Signature | Returns | |---|---|---| | `next` | `fn next(&mut self) -> Option>` | `Option` | | `with_checks` | `fn with_checks(self, val: bool) -> Self` | `Attributes` | ``` -------------------------------- ### Basic XML Writing in Rust Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/README.md Shows how to write basic XML structures using quick-xml's Writer. It constructs an XML document with a root element and text content. ```rust use quick_xml::writer::Writer; use quick_xml::events::{Event, BytesStart, BytesEnd, BytesText}; use std::io::Cursor; let mut writer = Writer::new(Cursor::new(Vec::new())); writer.write_event(Event::Start(BytesStart::new("root"))).unwrap(); writer.write_event(Event::Text(BytesText::new("content"))).unwrap(); writer.write_event(Event::End(BytesEnd::new("root"))).unwrap(); let output = writer.into_inner().into_inner(); assert_eq!(output, b"content"); ``` -------------------------------- ### Deserialize Enum Sequence Example Source: https://github.com/tafia/quick-xml/blob/master/Changelog.md Demonstrates deserializing a top-level sequence of enums. Ensure your XML structure matches the expected enum variants. ```xml ``` -------------------------------- ### Transform XML Content Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/README.md Reads XML events from an input string and writes them to an output buffer. This is a basic example of XML transformation or copying. ```Rust use quick_xml::reader::Reader; use quick_xml::writer::Writer; use quick_xml::events::Event; use std::io::Cursor; let mut reader = Reader::from_str(input_xml); let mut writer = Writer::new(Cursor::new(Vec::new())); let mut buf = Vec::new(); loop { buf.clear(); match reader.read_event_into(&mut buf)? { Event::Eof => break, e => writer.write_event(e.borrow())?, } } ``` -------------------------------- ### Writer Generic Trait Bounds Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/types.md The `W` type parameter for `Writer` must implement `io::Write`. Example shows usage with `Vec`. ```rust Writer> ``` -------------------------------- ### Basic XML Writing with Writer::new() Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/INDEX.md Illustrates basic XML writing using `Writer::new()`. This is suitable for generating simple XML structures. ```rust let mut writer = Writer::new(Vec::new()); writer.write_event(Event::Start(BytesStart::new("a"))); writer.write_event(Event::End(BytesEnd::new("a"))); let xml = String::from_utf8(writer.into_inner()).unwrap(); assert_eq!(xml, ""); ``` -------------------------------- ### Example: Missing End Tag Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/errors.md Represents reaching the end of the file (EOF) before a closing tag is found for an opened element. Ensure the XML document is complete. ```xml EOF in middle of element ``` -------------------------------- ### Reader Generic Trait Bounds Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/types.md The `R` type parameter for `Reader` must implement `io::Read` or `io::BufRead`. Example shows usage with `Cursor<&[u8]>`. ```rust Reader> ``` -------------------------------- ### BytesStart Ownership Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/events.md Methods for managing the ownership and borrowing of BytesStart instances. ```APIDOC ## BytesStart Ownership ### `into_owned` Converts to owned, detaching from input buffer. #### Signature `fn into_owned(self) -> BytesStart<'static>` ### `to_owned` Clones to owned without taking ownership. #### Signature `fn to_owned(&self) -> BytesStart<'static>` ### `borrow` Creates a borrowed reference. #### Signature `fn borrow(&self) -> BytesStart<'_>` ### `to_end` Creates matching closing tag. #### Signature `fn to_end(&self) -> BytesEnd<'_>` ``` -------------------------------- ### Package Project Source: https://github.com/tafia/quick-xml/blob/master/Changelog.md Packages the project for a final check before publishing. ```bash cargo package ``` -------------------------------- ### Configure NsReader Settings Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/namespace_reader.md Modify NsReader configuration by accessing the underlying Reader's configuration methods. This example shows how to enable text trimming and end name checking. ```rust reader.config_mut().trim_text(true); reader.config_mut().check_end_names = true; ``` -------------------------------- ### Example: Unclosed Reference Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/errors.md Occurs when an entity or character reference (e.g., '&entity') is not terminated with a semicolon ';'. This check is enabled by default ('allow_dangling_amp = false'). Complete references with ';' or enable 'allow_dangling_amp'. ```xml Text with &entity without ; ``` -------------------------------- ### quick-xml Benchmarking Results Source: https://github.com/tafia/quick-xml/blob/master/README.md Performance benchmarks comparing quick-xml against xml-rs and serde-xml-rs for XML parsing and serialization. Results indicate quick-xml is significantly faster. ```text // quick-xml benches test bench_quick_xml ... bench: 198,866 ns/iter (+/- 9,663) test bench_quick_xml_escaped ... bench: 282,740 ns/iter (+/- 61,625) test bench_quick_xml_namespaced ... bench: 389,977 ns/iter (+/- 32,045) // same bench with xml-rs test bench_xml_rs ... bench: 14,468,930 ns/iter (+/- 321,171) // serde-xml-rs vs serialize feature test bench_serde_quick_xml ... bench: 1,181,198 ns/iter (+/- 138,290) test bench_serde_xml_rs ... bench: 15,039,564 ns/iter (+/- 783,485) ``` -------------------------------- ### Zero-Copy XML Parsing Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/00_START_HERE.md Demonstrates how quick-xml's Reader borrows directly from input strings or byte arrays for efficient, zero-copy parsing. ```rust let xml = b"text"; let mut reader = Reader::from_reader(xml.as_ref()); // Events borrow from xml — no copying ``` -------------------------------- ### Automatically Resolve Namespace with read_resolved_event_into Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/namespace_reader.md Use `read_resolved_event_into` for convenience when you want the reader to automatically resolve namespaces for `Start`, `Empty`, and `End` events. Other events will return `Unbound` for the namespace. ```rust use quick_xml::events::Event; use quick_xml::name::ResolveResult::*; use quick_xml::reader::NsReader; let xml = r#" x content y content "#; let mut reader = NsReader::from_str(xml); let mut buf = Vec::new(); loop { buf.clear(); match reader.read_resolved_event_into(&mut buf) { Ok((Bound(ns), Event::Start(e))) => { println!("Element {} in namespace {}", String::from_utf8_lossy(e.local_name().as_ref()), String::from_utf8_lossy(ns.as_ref())); } Ok((_, Event::Eof)) => break, Ok(_) => {} Err(e) => eprintln!("Error: {}", e), } } ``` -------------------------------- ### Deserializing XML with Serde and quick-xml Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/00_START_HERE.md Illustrates deserializing XML into Rust structs using `quick_xml::de::from_str` and `serde::Deserialize`. Use `#[serde(rename = "@id")]` for attributes and `#[serde(rename = "$text")]` for text content. ```rust use serde::Deserialize; use quick_xml::de::from_str; #[derive(Deserialize)] struct Item { #[serde(rename = "@id")] id: u32, #[serde(rename = "$text")] value: String, } let xml = r###"hello"###; let item: Item = from_str(xml)?; assert_eq!(item.id, 123); assert_eq!(item.value, "hello"); ``` -------------------------------- ### Example: Double Hyphen in Comment Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/errors.md Indicates that a comment contains the '--' sequence, which is disallowed in XML comments. This check is disabled by default ('check_comments = true'). Remove '--' sequences or adjust their usage. ```xml ``` -------------------------------- ### Writing and Modifying XML Elements Source: https://github.com/tafia/quick-xml/blob/master/README.md Illustrates how to use quick-xml's Writer to create and modify XML. This snippet shows how to copy attributes from an existing element, add new attributes, and write events to an output buffer. ```Rust use quick_xml::events::{Event, BytesEnd, BytesStart}; use quick_xml::reader::Reader; use quick_xml::writer::Writer; use std::io::Cursor; let xml = r#"text"#; let mut reader = Reader::from_str(xml); reader.config_mut().trim_text(true); let mut writer = Writer::new(Cursor::new(Vec::new())); loop { match reader.read_event() { Ok(Event::Start(e)) if e.name().as_ref() == b"this_tag" => { // creates a new element ... alternatively we could reuse `e` by calling // `e.into_owned()` let mut elem = BytesStart::new("my_elem"); // collect existing attributes elem.extend_attributes(e.attributes().map(|attr| attr.unwrap())); // copy existing attributes, adds a new my-key="some value" attribute elem.push_attribute(("my-key", "some value")); // writes the event to the writer assert!(writer.write_event(Event::Start(elem)).is_ok()); }, Ok(Event::End(e)) if e.name().as_ref() == b"this_tag" => { assert!(writer.write_event(Event::End(BytesEnd::new("my_elem"))).is_ok()); }, Ok(Event::Eof) => break, // we can either move or borrow the event to write, depending on your use-case Ok(e) => assert!(writer.write_event(e).is_ok()), Err(e) => panic!("Error at position {}: {:?}", reader.error_position(), e), } } let result = writer.into_inner().into_inner(); let expected = r#"text"#; assert_eq!(result, expected.as_bytes()); ``` -------------------------------- ### Async Writer Generic Trait Bounds Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/types.md For async I/O, the `W` type parameter for async `Writer` must implement `tokio::io::AsyncWrite`. Example uses `tokio::io::BufWriter`. ```rust Writer> ``` -------------------------------- ### Async Reader Generic Trait Bounds Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/types.md For async I/O, the `R` type parameter for async `Reader` must implement `tokio::io::AsyncBufRead`. Example uses `tokio::io::BufReader`. ```rust Reader> ``` -------------------------------- ### Enable Serde Types for Event Serialization Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/features_and_config.md Enables Serde serialization and deserialization for Quick-XML's event types like `BytesStart` and `BytesEnd`. This is rarely needed and mostly useful for testing or advanced scenarios. ```rust #[cfg(feature = "serde-types")] { use serde::{Serialize, Deserialize}; use quick_xml::events::BytesStart; // Now BytesStart can be serialized/deserialized let start = BytesStart::new("element"); // let json = serde_json::to_string(&start)?; } ``` -------------------------------- ### Basic XML Reading with Reader::from_str() Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/INDEX.md Demonstrates how to perform basic XML reading from a string using the `Reader::from_str()` method. This is useful for simple XML parsing tasks. ```rust let xml = ""; let mut reader = Reader::from_str(xml); let mut buf = Vec::new(); let res = reader.read_event(&mut buf); assert!(res.is_ok()); assert_eq!(res.unwrap(), Event::Start(BytesStart::new("a"))); ``` -------------------------------- ### Handle quick-xml Errors Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/README.md Demonstrates how to handle errors returned by quick-xml reader/writer methods, which conform to `Result`. Specific error types like `Syntax` and `IllFormed` can be matched for detailed error reporting. ```rust use quick_xml::errors::Error; use quick_xml::reader::Reader; let mut reader = Reader::from_str(xml); let mut buf = Vec::new(); match reader.read_event_into(&mut buf) { Ok(event) => { /* process event */ } Err(Error::Syntax(e)) => eprintln!("Malformed XML: {}", e), Err(Error::IllFormed(e)) => eprintln!("Invalid XML: {}", e), Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### Parse XML with Namespaces using NsReader Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/namespace_reader.md Demonstrates how to use NsReader to parse an XML string with multiple namespaces. It shows how to resolve namespace URIs and process start elements belonging to specific namespaces. ```rust use quick_xml::events::Event; use quick_xml::name::ResolveResult::* use quick_xml::reader::NsReader; let xml = r#" Article "#; let mut reader = NsReader::from_str(xml); let mut buf = Vec::new(); loop { buf.clear(); match reader.read_resolved_event_into(&mut buf) { Ok((Bound(ns), Event::Start(e))) => { if ns.as_ref() == b"http://purl.org/rss/1.0/modules/content/" { println!("Found content:encoded element"); } else if ns.as_ref() == b"http://www.w3.org/2005/Atom" { println!("Found Atom element: {}", String::from_utf8_lossy(e.local_name().as_ref())); } } Ok((_, Event::Eof)) => break, Ok(_) => {} // Ignore other events Err(e) => eprintln!("Error: {}", e), } } ``` -------------------------------- ### Example: Mismatched End Tag Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/errors.md Triggered when a closing tag's name does not match the most recently opened tag's name. This check is enabled by default ('check_end_names = true'). Ensure tag names correspond. ```xml ``` -------------------------------- ### Generate Documentation Source: https://github.com/tafia/quick-xml/blob/master/Changelog.md Generates documentation for all features and checks for rendering issues. ```bash $env:RUSTDOCFLAGS="--cfg docsrs"; cargo +nightly doc --all-features ``` -------------------------------- ### Example: Unmatched End Tag Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/errors.md Occurs when a closing tag is encountered without a corresponding opening tag. This error is suppressed if 'allow_unmatched_ends' is true. Remove extra closing tags or add missing opening tags. ```xml ``` -------------------------------- ### Add quick-xml to Cargo.toml Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/README.md Add the quick-xml crate to your project's Cargo.toml file. You can include optional features like 'serialize', 'encoding', and 'async-tokio' as needed. ```toml [dependencies] quick-xml = "0.40" # With optional features quick-xml = { version = "0.40", features = ["serialize", "encoding", "async-tokio"] } ``` -------------------------------- ### Build XML Document from Scratch Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/writer.md Constructs an XML document programmatically by writing events sequentially. Useful for generating XML output without parsing existing data. Requires importing BytesStart, BytesText, BytesEnd, Event, Writer, and Cursor. ```Rust use quick_xml::events::{BytesStart, BytesText, BytesEnd, Event}; use quick_xml::writer::Writer; use std::io::Cursor; let mut writer = Writer::new(Cursor::new(Vec::new())); let mut root = BytesStart::new("root"); root.push_attribute(("version", "1.0")); writer.write_event(Event::Start(root)).unwrap(); writer.write_event(Event::Start(BytesStart::new("item"))).unwrap(); writer.write_event(Event::Text(BytesText::new("value"))).unwrap(); writer.write_event(Event::End(BytesEnd::new("item"))).unwrap(); writer.write_event(Event::End(BytesEnd::new("root"))).unwrap(); let output = String::from_utf8(writer.into_inner().into_inner()).unwrap(); assert_eq!(output, r# ``` -------------------------------- ### Reader Configuration Struct Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/features_and_config.md Defines the available configuration options for the Quick-xml reader. Defaults are provided in comments. ```rust pub struct Config { pub allow_dangling_amp: bool, // default: false pub allow_unmatched_ends: bool, // default: false pub check_comments: bool, // default: false pub check_end_names: bool, // default: true pub expand_empty_elements: bool, // default: false pub trim_markup_names_in_closing_tags: bool, // default: true pub trim_text_start: bool, // default: false pub trim_text_end: bool, // default: false } ``` -------------------------------- ### Check Minimum Supported Rust Version (MSRV) Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/features_and_config.md Use this command to check MSRV compliance for Quick-XML. ```bash cargo +1.79 check ``` -------------------------------- ### Complete XML Document Serialization and Deserialization Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/serialization.md Demonstrates how to deserialize an XML string into a Rust struct and then serialize that struct back into an XML string using quick-xml. Ensure the `serde` feature is enabled for this functionality. ```rust use serde::{Serialize, Deserialize}; use quick_xml::de::from_str; use quick_xml::se::to_string; #[derive(Serialize, Deserialize, Debug)] struct Config { #[serde(rename = "@version")] version: String, database: Database, servers: Vec, } #[derive(Serialize, Deserialize, Debug)] struct Database { #[serde(rename = "@type")] db_type: String, host: String, port: u16, } #[derive(Serialize, Deserialize, Debug)] struct Server { #[serde(rename = "@id")] id: u32, name: String, #[serde(rename = "@enabled")] enabled: bool, } let xml = r#" localhost 5432 web-01 db-01 "#; // Deserialize let config: Config = from_str(xml).unwrap(); assert_eq!(config.version, "1.0"); assert_eq!(config.database.port, 5432); assert_eq!(config.servers.len(), 2); // Serialize let serialized = to_string(&config).unwrap(); println!("{}", serialized); ``` -------------------------------- ### Config Methods Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/reader.md Helper methods for modifying multiple configuration settings at once. ```APIDOC #### Config Methods - `trim_text(&mut self, trim: bool)`: Set both `trim_text_start` and `trim_text_end` to the same value. - `enable_all_checks(&mut self, enable: bool)`: Set both `check_comments` and `check_end_names` to the same value. ``` -------------------------------- ### Convenience Constructors Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/reader.md Provides methods to create a Reader from string slices and byte slices, enabling zero-copy parsing. ```APIDOC ## Convenience Constructors (for &str and &[u8]) When `Reader` is specialized to work with `&str` or `&[u8]`, additional convenience methods are available: ### `from_str` - **Description**: Creates reader from a string slice, enabling zero-copy parsing. - **Parameter**: `s: &'a str` - **Returns**: `Reader>` ### `from_reader` - **Description**: Creates reader from a byte slice, enabling zero-copy parsing. - **Parameter**: `s: &'a [u8]` - **Returns**: `Reader>` ``` -------------------------------- ### Publish to Crates.io Source: https://github.com/tafia/quick-xml/blob/master/Changelog.md Publishes the project to the crates.io registry. ```bash cargo publish ``` -------------------------------- ### Iterating Attributes Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/events.md Demonstrates how to iterate over attributes of a BytesStart element. Ensure attributes are correctly added using `with_attributes` before iterating. ```rust use quick_xml::events::BytesStart; let start = BytesStart::new("element"); let start = start.with_attributes(vec![("id", "1"), ("class", "active")]); for attr in start.attributes() { let attr = attr.unwrap(); println!("{} = {:?}", String::from_utf8_lossy(attr.key.as_ref()), attr.value); } ``` -------------------------------- ### Enable Async I/O with Tokio Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/features_and_config.md Enables asynchronous I/O operations using the Tokio runtime and async/await syntax. Reader, Writer, and NsReader methods are extended with async versions. ```rust #[cfg(feature = "async-tokio")] { use tokio::fs::File; use quick_xml::reader::Reader; async fn parse_file() { let file = File::open("document.xml").await.unwrap(); let mut reader = Reader::from_reader(tokio::io::BufReader::new(file)); // Now use async methods // let event = reader.read_event_async().await; } } ``` -------------------------------- ### Writer Configuration Struct Source: https://github.com/tafia/quick-xml/blob/master/_autodocs/features_and_config.md Defines the configuration options for the Quick-xml writer, specifically for handling empty elements. ```rust pub struct Config { pub add_space_before_slash_in_empty_elements: bool, // default: false } ```