Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions crates/tinyxml2/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ name = "parse_file"
path = "../../examples/parse_file.rs"
required-features = ["std"]

[[example]]
name = "parse_string_error_handling"
path = "../../examples/parse_string.rs"
required-features = ["std"]

[[example]]
name = "build_dom"
path = "../../examples/build_dom.rs"
Expand Down
48 changes: 48 additions & 0 deletions examples/parse_string.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
//! Parses malformed XML strings and demonstrates how to handle different
//! [`XmlError`] variants with pattern matching.

use tinyxml2::{Document, XmlError};

fn main() {
try_parse("<root><child></root>", "mismatched tags");
try_parse("", "empty document");
try_parse("<root>", "unclosed tag");
}

fn try_parse(xml: &str, desc: &str) {
match Document::parse(xml) {
Ok(_doc) => {
// Successful parse
}
Err(e) => {
println!("--- {desc} ---");
println!(" error: {e}");
match &e {
XmlError::EmptyDocument => {
println!(" cause: the input contains no XML content");
}
XmlError::MismatchedElement {
expected,
found,
line,
} => {
println!(" cause: expected </{expected}>, found </{found}> at line {line}");
}
XmlError::Parse {
kind,
line,
message,
} => {
println!(" cause: {kind:?} error at line {line}");
if let Some(msg) = message {
println!(" detail: {msg}");
}
}
_ => {
println!(" cause: unexpected error β€” {e}");
}
}
println!();
}
}
}
Loading