Created
December 4, 2017 15:57
-
-
Save kindlychung/cbd4116e75fab8fe7e4c6c8c20dedb83 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate quick_xml; | |
use quick_xml::reader::Reader; | |
use quick_xml::events::Event; | |
fn main() { | |
let xml = r#"<tag1 att1 = "test"> | |
text_from_tag1 | |
<tag2><!--Test comment-->text1_from_tag2</tag2> | |
<tag2> | |
text2_from_tag2 | |
</tag2> | |
</tag1>"#; | |
let mut reader = Reader::from_str(xml); | |
reader.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 { | |
match reader.read_event(&mut buf) { | |
Ok(Event::Start(ref elem)) => { | |
match elem.name() { | |
b"tag1" => println!("attributes values: {:?}", | |
elem.attributes().map(|a| a.unwrap().value).collect::<Vec<_>>()), | |
b"tag2" => { | |
count += 1; | |
match reader.read_event(&mut buf) { | |
Ok(Event::Text(elem)) => txt.push(elem.unescape_and_decode(&reader).unwrap()), | |
_ => (), | |
} | |
}, | |
_ => (), | |
} | |
}, | |
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 | |
} | |
// if we don't keep a borrow elsewhere, we can clear the buffer to keep memory usage low | |
buf.clear(); | |
} | |
println!("Number of tag2: {}", count); | |
println!("Text snippets: \n{:?}", txt); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment