### Example Usage of a Public Function
Source: https://docs.rs/roxmltree/latest/scrape-examples-help.html
An example in examples/ex.rs demonstrating how to call a public function from another crate.
```rust
// examples/ex.rs
fn main() {
a_crate::a_func();
}
```
--------------------------------
### XML Document Statistics Example
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Node.html
This example demonstrates how to parse an XML file and calculate various statistics, including element count, attribute count, namespace count, and comment count. It also lists unique namespaces found in the document. Requires an input XML file path as a command-line argument.
```rust
use std::collections::HashSet;
fn main() {
let args: Vec<_> = std::env::args().collect();
if args.len() != 2 {
println!("Usage:\n\tcargo run --example stats -- input.xml");
std::process::exit(1);
}
let text = std::fs::read_to_string(&args[1]).unwrap();
let opt = roxmltree::ParsingOptions {
allow_dtd: true,
..roxmltree::ParsingOptions::default()
};
let doc = match roxmltree::Document::parse_with_options(&text, opt) {
Ok(v) => v,
Err(e) => {
println!("Error: {}.", e);
std::process::exit(1);
}
};
println!(
"Elements count: {}",
doc.root().descendants().filter(|n| n.is_element()).count()
);
let attrs_count: usize = doc.root().descendants().map(|n| n.attributes().len()).sum();
println!("Attributes count: {}", attrs_count);
let ns_count: usize = doc.root().descendants().map(|n| n.namespaces().len()).sum();
println!("Namespaces count: {}", ns_count);
let mut uris = HashSet::new();
for node in doc.root().descendants() {
for ns in node.namespaces() {
uris.insert((
ns.name().unwrap_or("""").to_string(),
ns.uri().to_string(),
));
}
}
println!("Unique namespaces count: {}", uris.len());
if !uris.is_empty() {
println!("Unique namespaces:");
for (key, value) in uris {
println!(" {:?}: {}", key, value);
}
}
println!(
"Comments count: {}",
doc.root().descendants().filter(|n| n.is_comment()).count()
);
println!("Comments:");
for node in doc.root().descendants().filter(|n| n.is_comment()) {
println!("{:?}", node.text().unwrap());
}
}
```
--------------------------------
### starts_with
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Checks if the string slice starts with a given pattern. The pattern can be a string slice, a character, a slice of characters, or a closure.
```APIDOC
## starts_with
### Description
Returns `true` if the given pattern matches a prefix of this string slice. Returns `false` if it does not.
### Method
`starts_with
(&self, pat: P) -> bool` where P: Pattern
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **pat** (P: Pattern) - Description: The pattern to check against the prefix of the string slice.
### Examples
```rust
let bananas = "bananas";
assert!(bananas.starts_with("bana"));
assert!(!bananas.starts_with("nana"));
```
```rust
let bananas = "bananas";
// Note that both of these assert successfully.
assert!(bananas.starts_with(&['b', 'a', 'n', 'a']));
assert!(bananas.starts_with(&['a', 'b', 'c', 'd']));
```
```
--------------------------------
### Parse XML and Print Element Tag Names and Positions
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Node.html
Parses an XML string from a file and iterates through all descendants, printing the tag name and text position for each element. This example demonstrates how to get the text position of a node's start range.
```rust
2fn main() {
3 let args: Vec<_> = std::env::args().collect();
4
5 if args.len() != 2 {
6 println!("Usage:\n\tcargo run --example print_pos -- input.xml");
7 std::process::exit(1);
8 }
9
10 let text = std::fs::read_to_string(&args[1]).unwrap();
11 let opt = roxmltree::ParsingOptions {
12 allow_dtd: true,
13 ..roxmltree::ParsingOptions::default()
14 };
15 let doc = match roxmltree::Document::parse_with_options(&text, opt) {
16 Ok(doc) => doc,
17 Err(e) => {
18 println!("Error: {}.", e);
19 return;
20 }
21 };
22
23 // TODO: finish
24 for node in doc.descendants() {
25 if node.is_element() {
26 println!(
27 "{:?} at "
28 , node.tag_name(),
29 doc.text_pos_at(node.range().start)
30 );
31 }
32 }
33}
```
--------------------------------
### Get range from start position
Source: https://docs.rs/roxmltree/latest/src/roxmltree/tokenizer.rs.html
Creates a `Range` representing the span from a given start position to the current stream position.
```rust
fn range_from(&self, start: usize) -> Range {
start..self.pos
}
```
--------------------------------
### trim_prefix
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Removes a prefix if the string starts with it, returning the rest of the string. This is an experimental API.
```APIDOC
## pub fn trim_prefix(&self, prefix: P) -> &str
### Description
Returns a string slice with the optional prefix removed.
If the string starts with the pattern `prefix`, returns the substring after the prefix. Unlike `strip_prefix`, this method always returns `&str` for easy method chaining, instead of returning `Option<&str>`.
If the string does not start with `prefix`, returns the original string unchanged.
The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **return value** (string slice) - The string slice with the prefix removed, or the original string if the prefix did not match.
### Response Example
```json
{
"example": "bar"
}
```
```
--------------------------------
### Finding Match Indices with `match_indices`
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Illustrates how to find the starting indices and the matched substrings for all non-overlapping occurrences of a pattern within a string using `match_indices`.
```rust
let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
assert_eq!(v, [(1, "abc"), (4, "abc")]);
let v: Vec<_> = "ababa".match_indices("aba").collect();
assert_eq!(v, [(0, "aba")]); // only the first `aba`
```
--------------------------------
### Iterator Implementation for AxisIter - Basic Methods
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.AxisIter.html
Core iterator methods for AxisIter, including retrieving the next item and its type, and getting size hints.
```rust
type Item = Node<'a, 'input>
```
```rust
fn next(&mut self) -> Option
```
```rust
fn size_hint(&self) -> (usize, Option)
```
--------------------------------
### Rust trim_left_matches Examples
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Demonstrates removing all occurrences of a pattern from the beginning of a string slice using `trim_left_matches`. This method is deprecated and superseded by `trim_start_matches`.
```rust
assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
```
--------------------------------
### ExpandedName Creation
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.ExpandedName.html
Demonstrates how to create an ExpandedName instance from static data.
```APIDOC
### `pub const fn from_static(uri: &'static str, name: &'static str) -> Self`
Create a new instance from static data.
##### Example
```rust
use roxmltree::ExpandedName;
const DAV_HREF: ExpandedName = ExpandedName::from_static("urn:ietf:params:xml:ns:caldav:", "calendar-data");
```
```
--------------------------------
### Example of Unexpected Entity Close Tag
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.Error.html
Illustrates an error where an entity value starts with a close tag, which is invalid XML structure.
```xml
'> ]>
&p;
```
--------------------------------
### Separators at string boundaries
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Demonstrates splitting a string where the separator ('0') appears at the beginning and end. This results in empty strings at the start and end of the output vector.
```Rust
let d: Vec<_> = "010".split("0").collect();
assert_eq!(d, &["", "1", ""]);
```
--------------------------------
### try_from
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.NamespaceIter.html
Performs the conversion.
```APIDOC
## fn try_from(value: U) -> Result>::Error>
### Description
Performs the conversion.
### Parameters
* `value`: The value to convert.
### Returns
A `Result` containing the converted value or an error.
```
--------------------------------
### Get Node Byte Range
Source: https://docs.rs/roxmltree/latest/src/roxmltree/lib.rs.html
Retrieves the byte range (start and end indices) of the node within the original XML document. Requires the 'positions' feature to be enabled.
```rust
/// Returns node's range in bytes in the original document.
#[cfg(feature = "positions")]
#[inline]
pub fn range(&self) -> Range {
self.d.range.clone()
}
```
--------------------------------
### Get Attribute Position (Deprecated)
Source: https://docs.rs/roxmltree/latest/src/roxmltree/lib.rs.html
Retrieves the starting byte position of an attribute in the original XML document. This method is deprecated and replaced by `range`. Use `range` for current and future compatibility.
```rust
#[cfg(feature = "positions")]
{
let doc = roxmltree::Document::parse(
""
).unwrap();
let attr = doc.root_element().attributes().next().unwrap();
// Example usage, though deprecated
// assert_eq!(attr.position(), 3);
}
```
--------------------------------
### XML Document Parsing and Statistics
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Node.html
This example demonstrates parsing an XML file with specific options (allowing DTDs) and then calculating statistics such as element count, attribute count, namespace count, and comment count. It also lists unique namespaces and comment texts.
```rust
use std::collections::HashSet;
fn main() {
let args: Vec<_> = std::env::args().collect();
if args.len() != 2 {
println!("Usage:\n\tcargo run --example stats -- input.xml");
std::process::exit(1);
}
let text = std::fs::read_to_string(&args[1]).unwrap();
let opt = roxmltree::ParsingOptions {
allow_dtd: true,
..roxmltree::ParsingOptions::default()
};
let doc = match roxmltree::Document::parse_with_options(&text, opt) {
Ok(v) => v,
Err(e) => {
println!("Error: {}.", e);
std::process::exit(1);
}
};
println!("Elements count: {}", doc.root().descendants().filter(|n| n.is_element()).count());
let attrs_count: usize = doc.root().descendants().map(|n| n.attributes().len()).sum();
println!("Attributes count: {}", attrs_count);
let ns_count: usize = doc.root().descendants().map(|n| n.namespaces().len()).sum();
println!("Namespaces count: {}", ns_count);
let mut uris = HashSet::new();
for node in doc.root().descendants() {
for ns in node.namespaces() {
uris.insert((
ns.name().unwrap_or("\"\"").to_string(),
ns.uri().to_string(),
));
}
}
println!("Unique namespaces count: {}", uris.len());
if !uris.is_empty() {
println!("Unique namespaces:");
for (key, value) in uris {
println!(" {:?}: {}", key, value);
}
}
println!("Comments count: {}", doc.root().descendants().filter(|n| n.is_comment()).count());
println!("Comments:");
for node in doc.root().descendants().filter(|n| n.is_comment()) {
println!("{:?}", node.text().unwrap());
}
}
```
--------------------------------
### Rust trim_prefix and trim_suffix Examples
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Demonstrates how to remove a prefix or suffix from a string slice using `trim_prefix` and `trim_suffix`. These methods return the original string if the prefix/suffix is not found and are useful for method chaining.
```rust
#![feature(trim_prefix_suffix)]
// Prefix present - removes it
assert_eq!("foo:bar".trim_prefix("foo:"), "bar");
assert_eq!("foofoo".trim_prefix("foo"), "foo");
// Prefix absent - returns original string
assert_eq!("foo:bar".trim_prefix("bar"), "foo:bar");
// Method chaining example
assert_eq!("".trim_prefix('<').trim_suffix('>'), "https://example.com/");
```
```rust
#![feature(trim_prefix_suffix)]
// Suffix present - removes it
assert_eq!("bar:foo".trim_suffix(":foo"), "bar");
assert_eq!("foofoo".trim_suffix("foo"), "foo");
// Suffix absent - returns original string
assert_eq!("bar:foo".trim_suffix("bar"), "bar:foo");
// Method chaining example
assert_eq!("".trim_prefix('<').trim_suffix('>'), "https://example.com/");
```
--------------------------------
### Splitting a String with a Limit and Closure Pattern (Forward)
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Demonstrates `splitn` with a closure pattern to split a string into a specified number of parts based on custom delimiter logic.
```rust
let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
assert_eq!(v, ["abc", "defXghi"]);
```
--------------------------------
### strip_prefix
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Removes a prefix exactly once if the string starts with the specified pattern. Returns None if the string does not start with the pattern.
```APIDOC
## pub fn strip_prefix(&self, prefix: P) -> Option<&str>
### Description
Returns a string slice with the prefix removed.
If the string starts with the pattern `prefix`, returns the substring after the prefix, wrapped in `Some`. Unlike `trim_start_matches`, this method removes the prefix exactly once.
If the string does not start with `prefix`, returns `None`.
The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **return value** (Option<&str>) - The substring after the prefix if found, otherwise None.
### Response Example
```json
{
"example": "bar"
}
```
### Examples
```rust
assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
assert_eq!("foo:bar".strip_prefix("bar"), None);
assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
```
```
--------------------------------
### Get Text Content of an Element
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Node.html
Extracts the text content of an element, which includes text from its first child text node. This is useful for getting the primary text associated with an element.
```rust
let doc = roxmltree::Document::parse("\
text
").unwrap();
assert_eq!(doc.root_element().text(),
Some("\n text\n"));
assert_eq!(doc.root_element().first_child().unwrap().text(),
Some("\n text\n"));
```
--------------------------------
### type_id
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.AxisIter.html
Gets the TypeId of self.
```APIDOC
## fn type_id(&self) -> TypeId
### Description
Gets the `TypeId` of `self`.
### Returns
A `TypeId` representing the type of `self`.
```
--------------------------------
### StringStorage Methods
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Provides details on the core methods directly callable on StringStorage instances.
```APIDOC
## fn deref(&self) -> &Self::Target
### Description
Dereferences the value.
### Method
`deref`
### Parameters
- `&self`: A reference to the StringStorage instance.
### Returns
- `&Self::Target`: A reference to the dereferenced target type (which is `str` in this case).
```
```APIDOC
## fn fmt(&self, f: &mut Formatter<'_>) -> Result
### Description
Formats the value using the given formatter.
### Method
`fmt`
### Parameters
- `&self`: A reference to the StringStorage instance.
- `f`: A mutable reference to a `Formatter`.
### Returns
- `Result`: A `Result` indicating success or failure of the formatting operation.
```
```APIDOC
## fn eq(&self, other: &Self) -> bool
### Description
Tests for `self` and `other` values to be equal.
### Method
`eq`
### Parameters
- `&self`: A reference to the first StringStorage instance.
- `other`: A reference to the second StringStorage instance.
### Returns
- `bool`: `true` if the values are equal, `false` otherwise.
```
```APIDOC
## fn ne(&self, other: &Rhs) -> bool
### Description
Tests for inequality between `self` and `other`.
### Method
`ne`
### Parameters
- `&self`: A reference to the first StringStorage instance.
- `other`: A reference to the other value for comparison.
### Returns
- `bool`: `true` if the values are not equal, `false` otherwise.
```
--------------------------------
### try_into
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.NamespaceIter.html
Performs the conversion.
```APIDOC
## fn try_into(self) -> Result>::Error>
### Description
Performs the conversion.
### Returns
A `Result` containing the converted value or an error.
```
--------------------------------
### Get String Slice
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Returns the StringStorage as a string slice.
```rust
pub fn as_str(&self) -> &str
```
--------------------------------
### Namespace::clone_from
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Namespace.html
Performs copy-assignment from a source Namespace to the current one. This is an efficient way to update an existing Namespace with the content of another.
```APIDOC
## Namespace::clone_from
### Description
Performs copy-assignment from `source`.
### Method
`clone_from`
### Parameters
* `source`: `&Self` - The Namespace to copy from.
### Returns
None
```
--------------------------------
### Public Function Declaration
Source: https://docs.rs/roxmltree/latest/scrape-examples-help.html
A public function declaration in src/lib.rs that can be used in examples.
```rust
// src/lib.rs
pub fn a_func() {}
```
--------------------------------
### take
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Descendants.html
Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner.
```APIDOC
## fn take(self, n: usize) -> Take
### Description
Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner.
### Parameters
- **n** (usize): The maximum number of elements to yield.
### Returns
- Take: An iterator that yields at most `n` elements.
```
--------------------------------
### Get character iterator
Source: https://docs.rs/roxmltree/latest/src/roxmltree/tokenizer.rs.html
Returns an iterator over the characters in the current span of the stream.
```rust
fn chars(&self) -> str::Chars<'input> {
self.span.as_str()[self.pos..self.end].chars()
}
```
--------------------------------
### Lookup Namespace URI by Prefix
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Node.html
Demonstrates how to find the URI associated with a given namespace prefix on an element.
```rust
let doc = roxmltree::Document::parse("").unwrap();
assert_eq!(doc.root_element().lookup_namespace_uri(Some("n")), Some("http://www.w3.org"));
```
--------------------------------
### Checking for String Prefix
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Shows how to determine if a string slice begins with a specified pattern, including substrings and character arrays.
```rust
let bananas = "bananas";
assert!(bananas.starts_with("bana"));
assert!(!bananas.starts_with("nana"));
```
```rust
let bananas = "bananas";
// Note that both of these assert successfully.
assert!(bananas.starts_with(&['b', 'a', 'n', 'a']));
assert!(bananas.starts_with(&['a', 'b', 'c', 'd']));
```
--------------------------------
### Get Attribute Value by Name
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Node.html
Retrieves the value of an attribute given its simple name.
```rust
let doc = roxmltree::Document::parse("").unwrap();
assert_eq!(doc.root_element().attribute("a"), Some("b"));
```
--------------------------------
### into
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.NamespaceIter.html
Calls `U::from(self)`. This conversion is whatever the implementation of `From for U` chooses to do.
```APIDOC
## fn into(self) -> U
### Description
Calls `U::from(self)`. This conversion is whatever the implementation of `From for U` chooses to do.
### Returns
The converted value.
```
--------------------------------
### next_siblings
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Node.html
Returns an iterator over the next sibling nodes, starting from the current node and moving forwards.
```APIDOC
## next_siblings
### Description
Returns an iterator over next sibling nodes starting at this node. Traverses horizontally forwards.
### Method
`&self` (method on Node)
### Returns
`AxisIter<'a, 'input>` - An iterator yielding next sibling nodes.
```
--------------------------------
### prev_siblings
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Node.html
Returns an iterator over the previous sibling nodes, starting from the current node and moving backwards.
```APIDOC
## prev_siblings
### Description
Returns an iterator over previous sibling nodes starting at this node. Traverses horizontally backwards.
### Method
`&self` (method on Node)
### Returns
`AxisIter<'a, 'input>` - An iterator yielding previous sibling nodes.
```
--------------------------------
### clone_to_uninit
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Attribute.html
Performs copy-assignment from self to dest. This is a nightly-only experimental API.
```APIDOC
## unsafe fn clone_to_uninit(&self, dest: *mut u8)
### Description
Performs copy-assignment from `self` to `dest`.
### Method
`unsafe fn`
### Parameters
#### Path Parameters
- `dest` (*mut u8) - Description: Pointer to the destination memory location.
```
--------------------------------
### partition
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Descendants.html
Consumes an iterator, creating two collections from it.
```APIDOC
## fn partition(self, f: F) -> (B, B)
### Description
Consumes an iterator, creating two collections from it.
### Parameters
- **f** (F): A closure that takes a reference to an item and returns `true` if the item should go into the first collection, `false` otherwise.
### Returns
- (B, B): A tuple containing two collections. The first collection contains items for which the predicate returned `true`, and the second contains items for which it returned `false`.
```
--------------------------------
### TextPos Struct
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.TextPos.html
Represents a position in text, indicating a row/line and a column. Positions start from 1:1.
```APIDOC
## Struct TextPos
### Description
Position in text. Position indicates a row/line and a column in the original text. Starting from 1:1.
### Fields
- `row`: u32
- `col`: u32
### Methods
#### fn new(row: u32, col: u32) -> TextPos
Constructs a new `TextPos`.
```
--------------------------------
### Get Namespace URI
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Namespace.html
Retrieves the namespace URI from a Namespace object. This is the actual identifier for the namespace.
```rust
let doc = roxmltree::Document::parse(
""
).unwrap();
assert_eq!(doc.root_element().namespaces().nth(0).unwrap().uri(), "http://www.w3.org");
```
--------------------------------
### Count XML Document Statistics
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Node.html
This example shows how to parse an XML document and calculate statistics such as the count of elements, attributes, namespaces, and comments. It also lists unique namespaces and the text of comments.
```rust
3fn main() {
4 let args: Vec<_> = std::env::args().collect();
5
6 if args.len() != 2 {
7 println!("Usage:\n\tcargo run --example stats -- input.xml");
8 std::process::exit(1);
9 }
10
11 let text = std::fs::read_to_string(&args[1]).unwrap();
12 let opt = roxmltree::ParsingOptions {
13 allow_dtd: true,
14 ..roxmltree::ParsingOptions::default()
15 };
16 let doc = match roxmltree::Document::parse_with_options(&text, opt) {
17 Ok(v) => v,
18 Err(e) => {
19 println!("Error: {}.", e);
20 std::process::exit(1);
21 }
22 };
23
24 println!(
25 "Elements count: {}",
26 doc.root().descendants().filter(|n| n.is_element()).count()
27 );
28
29 let attrs_count: usize = doc.root().descendants().map(|n| n.attributes().len()).sum();
30 println!("Attributes count: {}", attrs_count);
31
32 let ns_count: usize = doc.root().descendants().map(|n| n.namespaces().len()).sum();
33 println!("Namespaces count: {}", ns_count);
34
35 let mut uris = HashSet::new();
36 for node in doc.root().descendants() {
37 for ns in node.namespaces() {
38 uris.insert((
39 ns.name().unwrap_or("\"\").to_string(),
40 ns.uri().to_string(),
41 ));
42 }
43 }
44 println!("Unique namespaces count: {}", uris.len());
45 if !uris.is_empty() {
46 println!("Unique namespaces:");
47 for (key, value) in uris {
48 println!(" {:?}: {}", key, value);
49 }
50 }
51
52 println!(
53 "Comments count: {}",
54 doc.root().descendants().filter(|n| n.is_comment()).count()
55 );
56
57 println!("Comments:");
58 for node in doc.root().descendants().filter(|n| n.is_comment()) {
59 println!("{:?}", node.text().unwrap());
60 }
61}
```
--------------------------------
### Splitting a String with `rsplitn`
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Demonstrates splitting a string into a specified number of parts from the right using `rsplitn`. Supports string and character delimiters.
```rust
let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
assert_eq!(v, ["lamb", "little", "Mary had a"]);
let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
assert_eq!(v, ["leopard", "tiger", "lionX"]);
let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
assert_eq!(v, ["leopard", "lion::tiger"]);
```
--------------------------------
### Node::next_siblings
Source: https://docs.rs/roxmltree/latest/src/roxmltree/lib.rs.html
Provides an iterator over the following sibling nodes, starting from the current node and moving forwards.
```APIDOC
## Node::next_siblings
### Description
Returns an iterator over next sibling nodes starting at this node.
### Method
`AxisIter<'a, 'input>`
### Parameters
None
### Returns
- `AxisIter<'a, 'input>`: An iterator yielding next sibling nodes.
```
--------------------------------
### Splitting by a string pattern
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Demonstrates splitting a string slice using a multi-character string as a separator. Collects the substrings into a vector.
```Rust
let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);
```
--------------------------------
### Node::prev_siblings
Source: https://docs.rs/roxmltree/latest/src/roxmltree/lib.rs.html
Returns an iterator over the preceding sibling nodes, starting from the current node and moving backwards.
```APIDOC
## Node::prev_siblings
### Description
Returns an iterator over previous sibling nodes starting at this node.
### Method
`AxisIter<'a, 'input>`
### Parameters
None
### Returns
- `AxisIter<'a, 'input>`: An iterator yielding previous sibling nodes.
```
--------------------------------
### Parse XML String into Document
Source: https://docs.rs/roxmltree/latest/src/roxmltree/parse.rs.html
Parses an XML string into a Document structure. Initializes the document and context, then calls the tokenizer.
```rust
fn parse<'input>(text: &'input str, opt: ParsingOptions<'input>) -> Result> {
let nodes_capacity = memchr_iter(b'<', text.as_bytes()).count();
let attributes_capacity = memchr_iter(b'=', text.as_bytes()).count();
let mut doc = Document {
text,
nodes: Vec::with_capacity(nodes_capacity),
attributes: Vec::with_capacity(attributes_capacity),
namespaces: Namespaces::default(),
};
doc.nodes.push(NodeData {
parent: None,
prev_sibling: None,
next_subtree: None,
last_child: None,
kind: NodeKind::Root,
#[cfg(feature = "positions")]
range: 0..text.len(),
});
doc.namespaces
.push_ns(Some(NS_XML_PREFIX), StringStorage::Borrowed(NS_XML_URI))?;
let allow_dtd = opt.allow_dtd;
let mut ctx = Context {
opt,
namespace_start_idx: 1,
current_attributes: Vec::with_capacity(16),
entities: Vec::new(),
awaiting_subtree: Vec::new(),
parent_prefixes: vec![""],
after_text: Vec::with_capacity(1),
parent_id: NodeId::new(0),
tag_name: TagNameSpan::new_null(),
loop_detector: LoopDetector::default(),
doc,
};
tokenizer::parse(text, allow_dtd, &mut ctx)?;
let mut doc = ctx.doc;
if !doc.root().children().any(|n| n.is_element()) {
return Err(Error::NoRootNode);
}
if ctx.parent_prefixes.len() > 1 {
return Err(Error::UnclosedRootNode);
}
doc.nodes.shrink_to_fit();
doc.attributes.shrink_to_fit();
doc.namespaces.shrink_to_fit();
Ok(doc)
}
```
--------------------------------
### Slice StrSpan from position to current
Source: https://docs.rs/roxmltree/latest/src/roxmltree/tokenizer.rs.html
Extracts a `StrSpan` from a given starting position up to the current stream position.
```rust
fn slice_back_span(&self, pos: usize) -> StrSpan<'input> {
StrSpan::from_substr(self.span.text, pos, self.pos)
}
```
--------------------------------
### Lookup Default Namespace URI
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Node.html
Shows how to retrieve the default namespace URI for an element when no prefix is specified.
```rust
let doc = roxmltree::Document::parse("").unwrap();
assert_eq!(doc.root_element().lookup_namespace_uri(None), Some("http://www.w3.org"));
```
--------------------------------
### ancestors
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Node.html
Returns an iterator over the ancestor nodes, starting from the current node and moving upwards towards the root.
```APIDOC
## ancestors
### Description
Returns an iterator over ancestor nodes starting at this node. Traverses up the tree towards the root.
### Method
`&self` (method on Node)
### Returns
`AxisIter<'a, 'input>` - An iterator yielding ancestor nodes.
```
--------------------------------
### Get String Length in Bytes
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Returns the length of the string in bytes. This might not correspond to the human-perceived length.
```rust
let len = "foo".len();
assert_eq!(3, len);
assert_eq!("ƒoo".len(), 4); // fancy f!
assert_eq!("ƒoo".chars().count(), 3);
```
--------------------------------
### clone_from
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Performs copy-assignment from `source`.
```APIDOC
## fn clone_from(&mut self, source: &Self)
### Description
Performs copy-assignment from a source `StringStorage` value into `self`.
### Method
This is a method from the `Clone` trait implementation for `StringStorage`.
### Parameters
#### Path Parameters
- **source** (&Self) - Required - The `StringStorage` value to copy from.
```
--------------------------------
### Clone Implementation for PI
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.PI.html
Provides methods for cloning PI instances, allowing for duplication of processing instruction data.
```rust
fn clone(&self) -> PI<'input>
```
```rust
fn clone_from(&mut self, source: &Self)
```
--------------------------------
### Get u32 and usize from NodeId
Source: https://docs.rs/roxmltree/latest/src/roxmltree/lib.rs.html
Provides methods to retrieve the underlying u32 or usize representation of a NodeId.
```rust
impl NodeId {
/// Returns the `u32` representation of the `NodeId`.
#[inline]
pub fn get(self) -> u32 {
self.0.get() - 1
}
/// Returns the `usize` representation of the `NodeId`.
#[inline]
pub fn get_usize(self) -> usize {
self.get() as usize
}
}
```
--------------------------------
### Get current byte with error handling
Source: https://docs.rs/roxmltree/latest/src/roxmltree/tokenizer.rs.html
Retrieves the current byte, returning an error if the stream has ended.
```rust
pub fn curr_byte(&self) -> Result {
if self.at_end() {
return Err(Error::UnexpectedEndOfStream);
}
Ok(self.curr_byte_unchecked())
}
```
--------------------------------
### Splitting with a Closure Delimiter using `rsplitn`
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Shows how to use a closure as a delimiter with `rsplitn` to split a string based on multiple character conditions.
```rust
let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
assert_eq!(v, ["ghi", "abc1def"]);
```
--------------------------------
### Create New Owned String
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Creates a new owned StringStorage by copying from a string slice.
```rust
pub fn new_owned(s: &str) -> Self
```
--------------------------------
### Get Attribute Namespace
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Attribute.html
Retrieves the namespace URI of an attribute. Returns None for attributes without a namespace.
```rust
let doc = roxmltree::Document::parse(
""
).unwrap();
assert_eq!(doc.root_element().attributes().nth(0).unwrap().namespace(), None);
assert_eq!(doc.root_element().attributes().nth(1).unwrap().namespace(), Some("http://www.w3.org"));
```
--------------------------------
### Node::ancestors
Source: https://docs.rs/roxmltree/latest/src/roxmltree/lib.rs.html
Provides an iterator over the ancestor nodes, starting from the current node and moving upwards towards the root.
```APIDOC
## Node::ancestors
### Description
Returns an iterator over ancestor nodes starting at this node.
### Method
`AxisIter<'a, 'input>`
### Parameters
None
### Returns
- `AxisIter<'a, 'input>`: An iterator yielding ancestor nodes.
```
--------------------------------
### PartialEq Implementation for PI
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.PI.html
Allows for comparison of PI instances for equality.
```rust
fn eq(&self, other: &PI<'input>) -> bool
```
```rust
fn ne(&self, other: &Rhs) -> bool
```
--------------------------------
### trim_start
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Returns a string slice with leading whitespace removed. Whitespace is defined by the Unicode Derived Core Property `White_Space`.
```APIDOC
## pub fn trim_start(&self) -> &str
### Description
Returns a string slice with leading whitespace removed.
‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property `White_Space`, which includes newlines.
### Text directionality
A string is a sequence of bytes. `start` in this context means the first position of that byte string; for a left-to-right language like English or Russian, this will be left side, and for right-to-left languages like Arabic or Hebrew, this will be the right side.
### Examples
Basic usage:
```
let s = "\n Hello\tworld\t\n";
assert_eq!("Hello\tworld\t\n", s.trim_start());
```
Directionality:
```
let s = " English ";
assert!(Some('E') == s.trim_start().chars().next());
let s = " עברית ";
assert!(Some('ע') == s.trim_start().chars().next());
```
```
--------------------------------
### Slice string from position to current
Source: https://docs.rs/roxmltree/latest/src/roxmltree/tokenizer.rs.html
Extracts a string slice from a given starting position up to the current stream position.
```rust
fn slice_back(&self, pos: usize) -> &'input str {
self.span.slice_region(pos, self.pos)
}
```
--------------------------------
### Check if stream starts with specific bytes
Source: https://docs.rs/roxmltree/latest/src/roxmltree/tokenizer.rs.html
Checks if the stream, from the current position, begins with the provided byte slice.
```rust
fn starts_with(&self, text: &[u8]) -> bool {
self.span.text.as_bytes()[self.pos..self.end].starts_with(text)
}
```
--------------------------------
### as_str
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Returns the string slice as a `&str`. This is a nightly-only experimental API.
```APIDOC
## pub fn as_str(&self) -> &str
### Description
Returns the same string as a string slice `&str`. This method is useful for dereferencing other string-like types to string slices.
### Method
N/A (Method on string slice)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **&str**: The string slice representation.
#### Response Example
None
### Notes
- This is a nightly-only experimental API.
```
--------------------------------
### Extracting Namespaces from XML Document
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Namespace.html
This example demonstrates how to parse an XML document and iterate through its descendants to collect unique namespaces, including their names and URIs. It uses `HashSet` to store unique namespace entries.
```rust
use std::collections::HashSet;
fn main() {
let args: Vec<_> = std::env::args().collect();
if args.len() != 2 {
println!("Usage:\n\tcargo run --example stats -- input.xml");
std::process::exit(1);
}
let text = std::fs::read_to_string(&args[1]).unwrap();
let opt = roxmltree::ParsingOptions {
allow_dtd: true,
..roxmltree::ParsingOptions::default()
};
let doc = match roxmltree::Document::parse_with_options(&text, opt) {
Ok(v) => v,
Err(e) => {
println!("Error: {}.", e);
std::process::exit(1);
}
};
println!(
"Elements count: {}",
doc.root().descendants().filter(|n| n.is_element()).count()
);
let attrs_count: usize = doc.root().descendants().map(|n| n.attributes().len()).sum();
println!("Attributes count: {}", attrs_count);
let ns_count: usize = doc.root().descendants().map(|n| n.namespaces().len()).sum();
println!("Namespaces count: {}", ns_count);
let mut uris = HashSet::new();
for node in doc.root().descendants() {
for ns in node.namespaces() {
uris.insert((
ns.name().unwrap_or("\"\"").to_string(),
ns.uri().to_string(),
));
}
}
println!("Unique namespaces count: {}", uris.len());
if !uris.is_empty() {
println!("Unique namespaces:");
for (key, value) in uris {
println!(" {:?}: {}", key, value);
}
}
println!(
"Comments count: {}",
doc.root().descendants().filter(|n| n.is_comment()).count()
);
println!("Comments:");
for node in doc.root().descendants().filter(|n| n.is_comment()) {
println!("{:?}", node.text().unwrap());
}
}
```
--------------------------------
### StrSpan Definition
Source: https://docs.rs/roxmltree/latest/src/roxmltree/tokenizer.rs.html
Defines a `StrSpan` struct to represent a string slice along with its starting position in the original input.
```rust
/// A string slice.
///
/// Like `&str`, but also contains the position in the input XML
/// from which it was parsed.
#[must_use]
#[derive(Clone, Copy)]
pub struct StrSpan<'input> {
text: &'input str,
start: usize,
}
impl<'input> From<&'input str> for StrSpan<'input> {
```
--------------------------------
### ShortRange Conversion Methods
Source: https://docs.rs/roxmltree/latest/src/roxmltree/lib.rs.html
Provides methods to create a new ShortRange and convert it back to a Range.
```rust
impl ShortRange {
#[inline]
fn new(start: u32, end: u32) -> Self {
ShortRange { start, end }
}
#[inline]
fn to_urange(self) -> Range {
self.start as usize..self.end as usize
}
}
```
--------------------------------
### Safely Get Subslice
Source: https://docs.rs/roxmltree/latest/roxmltree/enum.StringStorage.html
Returns a subslice of the string, returning None if the indices are invalid or not on UTF-8 sequence boundaries.
```rust
let v = String::from("🗻∈🌏");
assert_eq!(Some("🗻"), v.get(0..4));
// indices not on UTF-8 sequence boundaries
assert!(v.get(1..).is_none());
assert!(v.get(..8).is_none());
// out of bounds
assert!(v.get(..42).is_none());
```
--------------------------------
### by_ref
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Descendants.html
Creates a “by reference” adapter for this instance of `Iterator`.
```APIDOC
## fn by_ref(&mut self) -> &mut Self
### Description
Creates a “by reference” adapter for this instance of `Iterator`.
### Returns
- &mut Self: A mutable reference to the iterator.
```
--------------------------------
### Get Attribute Value by Name
Source: https://docs.rs/roxmltree/latest/src/roxmltree/lib.rs.html
Retrieves the value of an attribute by its name. Handles both unqualified and qualified attribute names.
```rust
/// let doc = roxmltree::Document::parse("").unwrap();
///
/// assert_eq!(doc.root_element().attribute("a"), Some("b"));
```
```rust
/// let doc = roxmltree::Document::parse(
/// ""
/// ).unwrap();
///
/// assert_eq!(doc.root_element().attribute("a"), Some("b"));
/// assert_eq!(doc.root_element().attribute(("http://www.w3.org", "a")), Some("c"));
```
--------------------------------
### XML Statistics Gathering with Descendants
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.Node.html
This example demonstrates how to parse an XML document and gather statistics like element count, attribute count, namespace count, and comment count using the `descendants()` iterator. It shows how to filter nodes by type and extract specific information.
```rust
3fn main() {
4 let args: Vec<_> = std::env::args().collect();
5
6 if args.len() != 2 {
7 println!("Usage:\n\tcargo run --example stats -- input.xml");
8 std::process::exit(1);
9 }
10
11 let text = std::fs::read_to_string(&args[1]).unwrap();
12 let opt = roxmltree::ParsingOptions {
13 allow_dtd: true,
14 ..roxmltree::ParsingOptions::default()
15 };
16 let doc = match roxmltree::Document::parse_with_options(&text, opt) {
17 Ok(v) => v,
18 Err(e) => {
19 println!("Error: {}.", e);
20 std::process::exit(1);
21 }
22 };
23
24 println!(
25 "Elements count: {}",
26 doc.root().descendants().filter(|n| n.is_element()).count()
27 );
28
29 let attrs_count: usize = doc.root().descendants().map(|n| n.attributes().len()).sum();
30 println!("Attributes count: {}", attrs_count);
31
32 let ns_count: usize = doc.root().descendants().map(|n| n.namespaces().len()).sum();
33 println!("Namespaces count: {}", ns_count);
34
35 let mut uris = HashSet::new();
36 for node in doc.root().descendants() {
37 for ns in node.namespaces() {
38 uris.insert((
39 ns.name().unwrap_or("\"\"").to_string(),
40 ns.uri().to_string(),
41 ));
42 }
43 }
44 println!("Unique namespaces count: {}", uris.len());
45 if !uris.is_empty() {
46 println!("Unique namespaces:");
47 for (key, value) in uris {
48 println!(" {:?}: {}", key, value);
49 }
50 }
51
52 println!(
53 "Comments count: {}",
54 doc.root().descendants().filter(|n| n.is_comment()).count()
55 );
56
57 println!("Comments:");
58 for node in doc.root().descendants().filter(|n| n.is_comment()) {
59 println!("{:?}", node.text().unwrap());
60 }
61}
```
--------------------------------
### Get current byte without error checking
Source: https://docs.rs/roxmltree/latest/src/roxmltree/tokenizer.rs.html
Retrieves the current byte directly, assuming the position is valid.
```rust
pub fn curr_byte_unchecked(&self) -> u8 {
self.span.text.as_bytes()[self.pos]
}
```
--------------------------------
### Get Local Name of ExpandedName
Source: https://docs.rs/roxmltree/latest/roxmltree/struct.ExpandedName.html
Retrieves the local name of an ExpandedName. This is the name of the XML element without its namespace.
```rust
let doc = roxmltree::Document::parse("").unwrap();
assert_eq!(doc.root_element().tag_name().name(), "e");
```