Skip to content

Commit 51fd38f

Browse files
committed
Add example for buffered access when reading from a file
1 parent b09495a commit 51fd38f

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

examples/read_buffered.rs

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// This example demonstrates how a reader (for example when reading from a file)
2+
// can be buffered. In that case, data read from the file is written to a supplied
3+
// buffer and returned XML events borrow from that buffer.
4+
// That way, allocations can be kept to a minimum.
5+
6+
fn main() -> Result<(), quick_xml::Error> {
7+
use quick_xml::events::Event;
8+
use quick_xml::Reader;
9+
10+
let mut reader = Reader::from_file("tests/documents/document.xml")?;
11+
reader.trim_text(true);
12+
13+
let mut buf = Vec::new();
14+
15+
let mut count = 0;
16+
17+
loop {
18+
match reader.read_event_into(&mut buf) {
19+
Ok(Event::Start(ref e)) => {
20+
let name = e.name();
21+
let name = reader.decoder().decode(name.as_ref())?;
22+
println!("read start event {:?}", name.as_ref());
23+
count += 1;
24+
}
25+
Ok(Event::Eof) => break, // exits the loop when reaching end of file
26+
Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
27+
_ => (), // There are several other `Event`s we do not consider here
28+
}
29+
}
30+
31+
println!("read {} start events in total", count);
32+
33+
Ok(())
34+
}

0 commit comments

Comments
 (0)