(r#"
4.2
"#).unwrap(),
Root {
one: InternallyTaggedEnum::Unit,
two: InternallyTaggedEnum::Newtype(Newtype { attribute: 42 }),
three: InternallyTaggedEnum::Struct {
attribute: 42,
element: 4.2,
},
},
);
```
--------------------------------
### Reading HTML content with NsReader
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/reader/struct.NsReader.html
Example demonstrating how to read HTML-like content from an XML document by disabling end name checks.
```rust
use quick_xml::events::{BytesStart, Event};
use quick_xml::reader::NsReader;
let mut reader = NsReader::from_str(r#"
This is a HTML text
Usual XML rules does not apply inside it
For example, elements not needed to be "closed"
"#);
reader.config_mut().trim_text(true);
let start = BytesStart::new("html");
let end = start.to_end().into_owned();
// First, we read a start event...
assert_eq!(reader.read_event().unwrap(), Event::Start(start));
// ...and disable checking of end names because we expect HTML further...
reader.config_mut().check_end_names = false;
// ...then, we could read text content until close tag.
// This call will correctly handle nested elements.
let text = reader.read_text(end.name()).unwrap();
let text = text.decode().unwrap();
assert_eq!(text, r#"
This is a HTML text
Usual XML rules does not apply inside it
For example, elements not needed to be "closed"
"#);
assert!(matches!(text, Cow::Borrowed(_)));
// Now we can enable checks again
reader.config_mut().check_end_names = true;
```
--------------------------------
### Split slice into chunks
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/events/enum.Event.html
Methods for splitting slices into fixed-size chunks from the start or end.
```rust
let x = &[0, 1, 2];
if let Some((first, elements)) = x.split_first_chunk::<2>() {
assert_eq!(first, &[0, 1]);
assert_eq!(elements, &[2]);
}
assert_eq!(None, x.split_first_chunk::<4>());
```
```rust
let x = &[0, 1, 2];
if let Some((elements, last)) = x.split_last_chunk::<2>() {
assert_eq!(elements, &[0]);
assert_eq!(last, &[1, 2]);
}
assert_eq!(None, x.split_last_chunk::<4>());
```
--------------------------------
### Get first element
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/events/struct.BytesEnd.html
Returns the first element of the slice, or None if it is empty.
```rust
let v = [10, 40, 30];
assert_eq!(Some(&10), v.first());
let w: &[i32] = &[];
assert_eq!(None, w.first());
```
--------------------------------
### Split slice into chunks with as_chunks
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/events/enum.Event.html
Splits a slice into N-element arrays starting from the beginning. Panics if N is zero.
```rust
let slice = ['l', 'o', 'r', 'e', 'm'];
let (chunks, remainder) = slice.as_chunks();
assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);
assert_eq!(remainder, &['m']);
```
```rust
let slice = ['R', 'u', 's', 't'];
let (chunks, []) = slice.as_chunks::<2>() else {
panic!("slice didn't have even length")
};
assert_eq!(chunks, &[['R', 'u'], ['s', 't']]);
```
--------------------------------
### Extracting XML Encoding
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/events/struct.BytesDecl.html
Examples of extracting the encoding attribute from an XML declaration using the encoding() method.
```rust
use std::borrow::Cow;
use quick_xml::Error;
use quick_xml::events::{BytesDecl, BytesStart};
//
let decl = BytesDecl::from_start(BytesStart::from_content(" version='1.1'", 0));
assert!(decl.encoding().is_none());
//
let decl = BytesDecl::from_start(BytesStart::from_content(" encoding='utf-8'", 0));
match decl.encoding() {
Some(Ok(Cow::Borrowed(encoding))) => assert_eq!(encoding, b"utf-8"),
_ => assert!(false),
}
//
let decl = BytesDecl::from_start(BytesStart::from_content(" encoding='something_WRONG' encoding='utf-8'", 0));
match decl.encoding() {
Some(Ok(Cow::Borrowed(encoding))) => assert_eq!(encoding, b"something_WRONG"),
_ => assert!(false),
}
```
--------------------------------
### Skip XML content with read_to_end
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/reader/struct.Reader.html
Demonstrates skipping XML content after reading a start event, correctly handling nested elements of the same name.
```rust
use quick_xml::events::{BytesStart, Event};
use quick_xml::reader::Reader;
let mut reader = Reader::from_str(r#"
"#);
reader.config_mut().trim_text(true);
let start = BytesStart::new("outer");
let end = start.to_end().into_owned();
// First, we read a start event...
assert_eq!(reader.read_event().unwrap(), Event::Start(start));
// ...then, we could skip all events to the corresponding end event.
// This call will correctly handle nested elements.
// Note, however, that this method does not handle namespaces.
reader.read_to_end(end.name()).unwrap();
// At the end we should get an Eof event, because we ate the whole XML
assert_eq!(reader.read_event().unwrap(), Event::Eof);
```
--------------------------------
### Skip XML content with read_to_end_into
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/reader/struct.Reader.html
Shows how to skip nested XML content after consuming a start event, ensuring the reader reaches the corresponding end tag.
```rust
use quick_xml::events::{BytesStart, Event};
use quick_xml::reader::Reader;
let mut reader = Reader::from_str(r#"
"#);
reader.config_mut().trim_text(true);
let mut buf = Vec::new();
let start = BytesStart::new("outer");
let end = start.to_end().into_owned();
// First, we read a start event...
assert_eq!(reader.read_event_into(&mut buf).unwrap(), Event::Start(start));
// ...then, we could skip all events to the corresponding end event.
// This call will correctly handle nested elements.
// Note, however, that this method does not handle namespaces.
reader.read_to_end_into(end.name(), &mut buf).unwrap();
// At the end we should get an Eof event, because we ate the whole XML
assert_eq!(reader.read_event_into(&mut buf).unwrap(), Event::Eof);
```
--------------------------------
### pub fn read_resolved_event(&mut self) -> Result<(ResolveResult<'_>, Event<'i>)>
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/reader/struct.NsReader.html
Reads the next XML event from the buffer and resolves its namespace. Namespace resolution is performed for Start, Empty, and End events; other events return ResolveResult::Unbound.
```APIDOC
## pub fn read_resolved_event(&mut self) -> Result<(ResolveResult<'_>, Event<'i>)>
### Description
Reads the next event, borrows its content from the input buffer, and resolves its namespace if applicable. Namespace is resolved only for `Start`, `Empty`, and `End` events.
### Parameters
- **&mut self** - The NsReader instance.
### Returns
- **Result<(ResolveResult<'_>, Event<'i>)>** - A tuple containing the namespace resolution result and the XML event.
```
--------------------------------
### Demonstrate BytesStart Deref and Content Access
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/events/struct.BytesStart.html
Shows how BytesStart implements Deref to [u8] and how to create an event from content.
```rust
// Remember, that \ at the end of string literal strips
// all space characters to the first non-space character
let mut reader = Reader::from_str("\
\
"
);
let content = "element a1 = 'val1' a2=\"val2\" ";
let event = BytesStart::from_content(content, 7);
assert_eq!(reader.read_event().unwrap(), Event::Empty(event.borrow()));
assert_eq!(reader.read_event().unwrap(), Event::Start(event.borrow()));
// deref coercion of &BytesStart to &[u8]
assert_eq!(&event as &[u8], content.as_bytes());
// AsRef<[u8]> for &T + deref coercion
assert_eq!(event.as_ref(), content.as_bytes());
```
--------------------------------
### XML Element Representation
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/events/index.html
Example of an XML element structure that is decomposed into Start, Text, and End events.
```xml
Inner text
```
--------------------------------
### UnquotedValue Error Example
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/events/attributes/enum.AttrError.html
Input example that triggers an UnquotedValue error when an attribute value is not enclosed in quotes.
```xml
```
--------------------------------
### Reading XML events with Reader
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/reader/struct.Reader.html
Demonstrates how to initialize a Reader from a string, configure text trimming, and iterate through XML events using read_event_into.
```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();
}
```
--------------------------------
### Initialize Serializer with Root Tag
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/se/struct.Serializer.html
Demonstrates creating a Serializer with a custom root tag for both primitive types and structs.
```rust
let mut buffer = String::new();
let ser = Serializer::with_root(&mut buffer, Some("root")).unwrap();
"node".serialize(ser).unwrap();
assert_eq!(buffer, "node");
```
```rust
#[derive(Debug, PartialEq, Serialize)]
struct Struct {
question: String,
answer: u32,
}
let mut buffer = String::new();
let ser = Serializer::with_root(&mut buffer, Some("root")).unwrap();
let data = Struct {
question: "The Ultimate Question of Life, the Universe, and Everything".into(),
answer: 42,
};
data.serialize(ser).unwrap();
assert_eq!(
buffer,
"\
The Ultimate Question of Life, the Universe, and Everything\
42\
"
);
```
--------------------------------
### Create XML elements with Writer
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/writer/struct.Writer.html
Demonstrates using create_element to write empty tags, tags with attributes, and nested content.
```rust
use quick_xml::events::{BytesStart, BytesText, Event};
use quick_xml::writer::Writer;
use quick_xml::Error;
use std::io::Cursor;
let mut writer = Writer::new(Cursor::new(Vec::new()));
// writes
writer.create_element("tag")
.with_attribute(("attr1", "value1")) // chain `with_attribute()` calls to add many attributes
.write_empty()?;
// writes with some text inside
writer.create_element("tag")
.with_attributes(vec![("attr1", "value1"), ("attr2", "value2")].into_iter()) // or add attributes from an iterator
.write_text_content(BytesText::new("with some text inside"))?;
// writes appleorange
writer.create_element("tag")
// We need to provide error type, because it is not named somewhere explicitly
.write_inner_content(|writer| {
let fruits = ["apple", "orange"];
for (quant, item) in fruits.iter().enumerate() {
writer
.create_element("fruit")
.with_attribute(("quantity", quant.to_string().as_str()))
.write_text_content(BytesText::new(item))?;
}
Ok(())
})?;
```
--------------------------------
### read_text_into
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/reader/struct.Reader.html
Reads content between start and end tags, including any markup, using a provided buffer as intermediate storage. This method is intended to be called after a Start event has been read.
```APIDOC
## pub fn read_text_into<'b>(&mut self, end: QName<'_>, buf: &'b mut Vec) -> Result>
### Description
Reads content between start and end tags, including any markup using provided buffer as intermediate storage for events content. This function is supposed to be called after you already read a Start event.
### Parameters
- **end** (QName) - The name of the end tag to stop reading at.
- **buf** (&mut Vec) - The buffer used to store the read content.
```
--------------------------------
### pub fn read_text(&mut self, end: QName<'_>) -> Result>
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/reader/struct.NsReader.html
Reads content between start and end tags, including any markup. This function is intended to be called after reading a Start event and manages nested elements with the same name.
```APIDOC
## read_text(end: QName<'_>)
### Description
Reads content between start and end tags, including any markup. This method does not unescape the read data and returns the content as-is from the XML document.
### Parameters
- **end** (QName<'_>) - Required - The name of the end tag to read until.
### Returns
- **Result>** - The content read between the tags or an error if reading fails.
```
--------------------------------
### Writer::new
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/writer/struct.Writer.html
Creates a new Writer instance from a generic writer.
```APIDOC
## pub const fn new(inner: W) -> Writer
### Description
Creates a `Writer` from a generic writer.
```
--------------------------------
### Get slice length
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/events/struct.BytesEnd.html
Returns the number of elements in the slice.
```rust
let a = [1, 2, 3];
assert_eq!(a.len(), 3);
```
--------------------------------
### Add and resolve namespace bindings
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/name/struct.NamespaceResolver.html
Demonstrates adding namespace declarations and resolving element names, including handling default and named prefixes.
```rust
let mut resolver = NamespaceResolver::default();
// names without prefix are unbound by default
assert_eq!(
resolver.resolve_element(QName(b"name")).0,
ResolveResult::Unbound,
);
// names with undeclared prefix are unknown
assert_eq!(
resolver.resolve_element(QName(b"ns:name")).0,
ResolveResult::Unknown(b"ns".to_vec()),
);
resolver.add(PrefixDeclaration::Default, Namespace(b"example.com"));
resolver.add(PrefixDeclaration::Named(b"ns"), Namespace(b"my:namespace"));
assert_eq!(
resolver.resolve_element(QName(b"name")).0,
ResolveResult::Bound(Namespace(b"example.com")),
);
assert_eq!(
resolver.resolve_element(QName(b"ns:name")).0,
ResolveResult::Bound(Namespace(b"my:namespace")),
);
// adding empty namespace clears the binding
resolver.add(PrefixDeclaration::Default, Namespace(b""));
resolver.add(PrefixDeclaration::Named(b"ns"), Namespace(b""));
assert_eq!(
resolver.resolve_element(QName(b"name")).0,
ResolveResult::Unbound,
);
assert_eq!(
resolver.resolve_element(QName(b"ns:name")).0,
ResolveResult::Unknown(b"ns".to_vec()),
);
```
--------------------------------
### BinaryStream::get_mut
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/reader/struct.BinaryStream.html
Gets a mutable reference to the underlying reader.
```APIDOC
## pub fn get_mut(&mut self) -> &mut R
### Description
Gets a mutable reference to the underlying reader. Note: Avoid reading directly from this returned reference as it will not update the reader's position, leading to incorrect error reporting.
```
--------------------------------
### Write XML events using Writer
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/writer/struct.Writer.html
Demonstrates how to read XML events from a Reader and write them to a Writer, including modifying element names and attributes.
```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);
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.borrow()).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());
```
--------------------------------
### Get last element
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/events/struct.BytesEnd.html
Returns the last element of the slice, or None if it is empty.
```rust
let v = [10, 40, 30];
assert_eq!(Some(&30), v.last());
let w: &[i32] = &[];
assert_eq!(None, w.last());
```
--------------------------------
### Convert QName to LocalName
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/name/struct.LocalName.html
Demonstrates creating a LocalName from a QName, which extracts the local part of the name.
```rust
let local: LocalName = QName(b"unprefixed").into();
assert_eq!(local.as_ref(), b"unprefixed");
let local: LocalName = QName(b"some:prefix").into();
assert_eq!(local.as_ref(), b"prefix");
```
--------------------------------
### Read XML events and binary data with Reader
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/reader/struct.Reader.html
Demonstrates reading XML events and switching to the underlying stream to read binary data while maintaining position synchronization.
```rust
assert_eq!(
(reader.read_event().unwrap(), reader.buffer_position()),
// 5 - end of the ``
(Event::Start(BytesStart::new("tag")), 5)
);
// Reading directly from underlying reader will not update position
// let mut inner = reader.get_mut();
// Reading from the stream() advances position
let mut inner = reader.stream();
// Read binary data. We must know its size
let mut binary = [0u8; 16];
inner.read_exact(&mut binary).unwrap();
assert_eq!(&binary, b"binary << data&>");
// 21 - end of the `binary << data&>`
assert_eq!(inner.offset(), 21);
assert_eq!(reader.buffer_position(), 21);
assert_eq!(
(reader.read_event().unwrap(), reader.buffer_position()),
// 27 - end of the ``
(Event::End(BytesEnd::new("tag")), 27)
);
assert_eq!(reader.read_event().unwrap(), Event::Eof);
```
--------------------------------
### Trim ASCII whitespace from start
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/events/struct.BytesEnd.html
Removes leading ASCII whitespace bytes from the slice.
```rust
assert_eq!(b" \t hello world\n".trim_ascii_start(), b"hello world\n");
assert_eq!(b" ".trim_ascii_start(), b"");
assert_eq!(b"".trim_ascii_start(), b"");
```
--------------------------------
### Using BytesDecl with Reader
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/events/struct.BytesDecl.html
Demonstrates how to create a BytesDecl from content and verify its deref behavior.
```rust
let mut reader = Reader::from_str("");
let content = "xml version = '1.0' ";
let event = BytesDecl::from_start(BytesStart::from_content(content, 3));
assert_eq!(reader.read_event().unwrap(), Event::Decl(event.borrow()));
// deref coercion of &BytesDecl to &[u8]
assert_eq!(&event as &[u8], content.as_bytes());
// AsRef<[u8]> for &T + deref coercion
assert_eq!(event.as_ref(), content.as_bytes());
```
--------------------------------
### from_file
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/reader/struct.Reader.html
Creates an XML reader from a file path.
```APIDOC
## pub fn from_file>(path: P) -> Result
### Description
Creates an XML reader from a file path.
### Parameters
- **path** (P) - The path to the XML file.
```
--------------------------------
### XML structure for overlapped lists
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/index.html
Example XML structure that benefits from the overlapped-lists feature when deserializing.
```xml
```
--------------------------------
### read_text
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/reader/struct.Reader.html
Reads content between start and end tags, including markup, without unescaping the data.
```APIDOC
## pub fn read_text(&mut self, end: QName<'_>) -> Result>
### Description
Reads content between start and end tags, including any markup, as-is. This method should be called after a `Start` event has been consumed and does not perform unescaping.
### Parameters
- **end** (QName<'_>) - Required - The name of the end element in the reader encoding.
### Returns
- **Result>** - The content between the tags decoded using the current XML decoder.
```
--------------------------------
### Split slice from the end
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/events/enum.Event.html
Splits a slice into an iterator starting from the end, excluding the matched elements.
```rust
let slice = [11, 22, 33, 0, 44, 55];
let mut iter = slice.rsplit(|num| *num == 0);
assert_eq!(iter.next().unwrap(), &[44, 55]);
assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
assert_eq!(iter.next(), None);
```
```rust
let v = &[0, 1, 1, 2, 3, 5, 8];
let mut it = v.rsplit(|n| *n % 2 == 0);
assert_eq!(it.next().unwrap(), &[]);
assert_eq!(it.next().unwrap(), &[3, 5]);
assert_eq!(it.next().unwrap(), &[1, 1]);
assert_eq!(it.next().unwrap(), &[]);
assert_eq!(it.next(), None);
```
--------------------------------
### config / config_mut
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/reader/struct.NsReader.html
Accesses the parser configuration.
```APIDOC
## pub const fn config(&self) -> &Config
## pub fn config_mut(&mut self) -> &mut Config
### Description
Provides access to the parser configuration, allowing for modification of settings like text trimming or end name checking.
```
--------------------------------
### Usage of BytesPI with Deref and AsRef
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/events/struct.BytesPI.html
Demonstrates how BytesPI implements Deref and AsRef to access the underlying content of the processing instruction.
```rust
let mut reader = Reader::from_str(":-<~ ?>");
let content = "processing instruction >:-<~ ";
let event = BytesPI::new(content);
assert_eq!(reader.read_event().unwrap(), Event::PI(event.borrow()));
// deref coercion of &BytesPI to &[u8]
assert_eq!(&event as &[u8], content.as_bytes());
// AsRef<[u8]> for &T + deref coercion
assert_eq!(event.as_ref(), content.as_bytes());
```
--------------------------------
### DEFAULT_MAX_DECLARATIONS_PER_ELEMENT definition
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/name/constant.DEFAULT_MAX_DECLARATIONS_PER_ELEMENT.html
The default limit for xmlns declarations accepted by NamespaceResolver::push on a single start tag.
```rust
pub const DEFAULT_MAX_DECLARATIONS_PER_ELEMENT: usize = 256;
```
--------------------------------
### Skip XML content asynchronously
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/reader/struct.Reader.html
Uses read_to_end_into_async to skip nested XML elements after reading a start event.
```rust
use quick_xml::events::{BytesStart, Event};
use quick_xml::reader::Reader;
let mut reader = Reader::from_reader(r#"
"#.as_bytes());
reader.config_mut().trim_text(true);
let mut buf = Vec::new();
let start = BytesStart::new("outer");
let end = start.to_end().into_owned();
// First, we read a start event...
assert_eq!(reader.read_event_into_async(&mut buf).await.unwrap(), Event::Start(start));
// ...then, we could skip all events to the corresponding end event.
// This call will correctly handle nested elements.
// Note, however, that this method does not handle namespaces.
reader.read_to_end_into_async(end.name(), &mut buf).await.unwrap();
// At the end we should get an Eof event, because we ate the whole XML
assert_eq!(reader.read_event_into_async(&mut buf).await.unwrap(), Event::Eof);
```
--------------------------------
### Read documents with DecodingReader
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/encoding/struct.DecodingReader.html
Shows how to integrate DecodingReader with a Reader to process XML documents with non-UTF-8 encodings.
```rust
use quick_xml::encoding::DecodingReader;
use quick_xml::events::Event;
use quick_xml::reader::Reader;
let xml = to_utf16le_with_bom("");
let mut decoder = DecodingReader::new(xml.as_ref());
let mut reader = Reader::from_reader(decoder);
let mut buf = Vec::new();
loop {
buf.clear();
match reader.read_event_into(&mut buf).unwrap() {
Event::Decl(e) => {
// If XML declaration contains unknown encoding name, None is returned
match e.encoder() {
Some(encoding) => reader.get_mut().set_encoding(encoding),
None => panic!("Unsupported encoding {:?}", e.encoding()),
}
}
Event::Eof => break,
_ => {}
}
}
```
--------------------------------
### Deref and AsRef implementation for BytesRef
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/events/struct.BytesRef.html
Demonstrates how BytesRef implements Deref and AsRef to access the underlying byte content.
```rust
let mut reader = Reader::from_str(r#"&entity;"#);
let content = "entity";
let event = BytesRef::new(content);
assert_eq!(reader.read_event().unwrap(), Event::GeneralRef(event.borrow()));
// deref coercion of &BytesRef to &[u8]
assert_eq!(&event as &[u8], content.as_bytes());
// AsRef<[u8]> for &T + deref coercion
assert_eq!(event.as_ref(), content.as_bytes());
```
--------------------------------
### Using text_content with serde(with)
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/serde_helpers/text_content/index.html
Demonstrates using the text_content helper to serialize and deserialize an enum variant as the text content of an XML element.
```rust
use quick_xml::de::from_str;
use quick_xml::se::to_string;
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, PartialEq, Debug)]
enum SomeEnum {
// Default implementation serializes enum as an `` element
EnumValue,
...
}
#[derive(Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename = "some-container")]
struct SomeContainer {
#[serde(with = "quick_xml::serde_helpers::text_content")]
field: SomeEnum,
}
let container = SomeContainer {
field: SomeEnum::EnumValue,
};
let xml = "\
\
EnumValue\
";
assert_eq!(to_string(&container).unwrap(), xml);
assert_eq!(from_str::(xml).unwrap(), container);
```
--------------------------------
### Split slice from the end into limited number of items
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/events/enum.Event.html
Splits a slice into at most n items starting from the end based on a predicate.
```rust
let v = [10, 40, 30, 20, 60, 50];
for group in v.rsplitn(2, |num| *num % 3 == 0) {
println!("{group:?}");
}
```
--------------------------------
### from_str
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/reader/struct.Reader.html
Creates an XML reader from a string slice.
```APIDOC
## pub fn from_str(s: &'a str) -> Self
### Description
Creates an XML reader from a string slice.
### Parameters
- **s** (&'a str) - The string slice containing XML data.
```
--------------------------------
### Manage namespace nesting levels
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/name/struct.NamespaceResolver.html
Shows how to manipulate the internal nesting level of the resolver using push, pop, and set_level methods.
```rust
let mut resolver = NamespaceResolver::default();
assert_eq!(resolver.level(), 0);
resolver.push(&BytesStart::new("tag"));
assert_eq!(resolver.level(), 1);
resolver.set_level(10);
assert_eq!(resolver.level(), 10);
resolver.pop();
assert_eq!(resolver.level(), 9);
resolver.set_level(0);
assert_eq!(resolver.level(), 0);
// pop from empty resolver does nothing
resolver.pop();
assert_eq!(resolver.level(), 0);
```
--------------------------------
### Split slice into chunks from the end with as_rchunks
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/events/enum.Event.html
Splits a slice into N-element arrays starting from the end. Panics if N is zero.
```rust
let slice = ['l', 'o', 'r', 'e', 'm'];
let (remainder, chunks) = slice.as_rchunks();
assert_eq!(remainder, &['l']);
assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
```
--------------------------------
### Verify BytesCData content and deref behavior
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/events/struct.BytesCData.html
Demonstrates how to create a BytesCData instance and verify its content via deref coercion and AsRef implementation.
```rust
let mut reader = Reader::from_str("");
let content = " CDATA section ";
let event = BytesCData::new(content);
assert_eq!(reader.read_event().unwrap(), Event::CData(event.borrow()));
// deref coercion of &BytesCData to &[u8]
assert_eq!(&event as &[u8], content.as_bytes());
// AsRef<[u8]> for &T + deref coercion
assert_eq!(event.as_ref(), content.as_bytes());
```
--------------------------------
### Get pointer range of slice
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/events/struct.BytesEnd.html
Returns a half-open range of raw pointers spanning the slice, useful for foreign interfaces.
```rust
let a = [1, 2, 3];
let x = &a[1] as *const _;
let y = &5 as *const _;
assert!(a.as_ptr_range().contains(&x));
assert!(!a.as_ptr_range().contains(&y));
```
--------------------------------
### Read and resolve XML events
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/reader/struct.NsReader.html
Shows how to iterate through XML events using read_event and resolve element namespaces manually using the resolver.
```rust
use quick_xml::events::Event;
use quick_xml::name::{Namespace, ResolveResult::*};
use quick_xml::reader::NsReader;
let mut reader = NsReader::from_str(r#"
Test
Test 2
"#);
reader.config_mut().trim_text(true);
let mut count = 0;
let mut txt = Vec::new();
loop {
match reader.read_event().unwrap() {
Event::Start(e) => {
count += 1;
let (ns, local) = reader.resolver().resolve_element(e.name());
match local.as_ref() {
b"tag1" => assert_eq!(ns, Bound(Namespace(b"www.xxxx"))),
b"tag2" => assert_eq!(ns, Bound(Namespace(b"www.yyyy"))),
_ => unreachable!(),
}
}
Event::Text(e) => {
txt.push(e.decode().unwrap().into_owned())
}
Event::Eof => break,
_ => (),
}
}
assert_eq!(count, 3);
assert_eq!(txt, vec!["Test".to_string(), "Test 2".to_string()]);
```
--------------------------------
### Extract prefix from QName
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/name/struct.QName.html
Demonstrates retrieving the namespace prefix from a qualified name, returning None if no prefix exists.
```rust
let simple = QName(b"simple-name");
assert_eq!(simple.prefix(), None);
let qname = QName(b"prefix:simple-name");
assert_eq!(qname.prefix().as_ref().map(|n| n.as_ref()), Some(b"prefix".as_ref()));
```
--------------------------------
### Read Resolved Events with NsReader
Source: https://docs.rs/quick-xml/0.41.0/quick_xml/reader/struct.NsReader.html
Demonstrates reading XML events while automatically resolving namespaces for Start, Empty, and End tags.
```rust
use quick_xml::events::Event;
use quick_xml::name::{Namespace, QName, ResolveResult::*};
use quick_xml::reader::NsReader;
let mut reader = NsReader::from_str(r#"
Test
Test 2
"#);
reader.config_mut().trim_text(true);
let mut count = 0;
let mut txt = Vec::new();
loop {
match reader.read_resolved_event().unwrap() {
(Bound(Namespace(b"www.xxxx")), Event::Start(e)) => {
count += 1;
assert_eq!(e.local_name(), QName(b"tag1").into());
}
(Bound(Namespace(b"www.yyyy")), Event::Start(e)) => {
count += 1;
assert_eq!(e.local_name(), QName(b"tag2").into());
}
(_, Event::Start(_)) => unreachable!(),
(_, Event::Text(e)) => {
txt.push(e.decode().unwrap().into_owned())
}
(_, Event::Eof) => break,
_ => (),
}
}
assert_eq!(count, 3);
assert_eq!(txt, vec!["Test".to_string(), "Test 2".to_string()]);
```