Skip to content

Commit

Permalink
Add example for buffered access when reading from a file
Browse files Browse the repository at this point in the history
  • Loading branch information
999eagle committed Jul 18, 2022
1 parent b09495a commit 51fd38f
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions examples/read_buffered.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// This example demonstrates how a reader (for example when reading from a file)
// can be buffered. In that case, data read from the file is written to a supplied
// buffer and returned XML events borrow from that buffer.
// That way, allocations can be kept to a minimum.

fn main() -> Result<(), quick_xml::Error> {
use quick_xml::events::Event;
use quick_xml::Reader;

let mut reader = Reader::from_file("tests/documents/document.xml")?;
reader.trim_text(true);

let mut buf = Vec::new();

let mut count = 0;

loop {
match reader.read_event_into(&mut buf) {
Ok(Event::Start(ref e)) => {
let name = e.name();
let name = reader.decoder().decode(name.as_ref())?;
println!("read start event {:?}", name.as_ref());
count += 1;
}
Ok(Event::Eof) => break, // exits the loop when reaching end of file
Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
_ => (), // There are several other `Event`s we do not consider here
}
}

println!("read {} start events in total", count);

Ok(())
}

0 comments on commit 51fd38f

Please sign in to comment.