High performance xml pull reader/writer.
Syntax is inspired by xml-rs.
toml
[dependencies]
quick-xml = "0.7.0"
rust
extern crate quick_xml;
```rust use quickxml::reader::Reader use quickxml::events::Event;
let xml = r#"
let mut reader = Reader::fromstr(xml); reader.trimtext(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.readevent(&mut buf) {
// for triggering namespaced events, use this instead:
// match reader.readnamespacedevent(&mut buf) {
Ok(Event::Start(ref e)) => {
// for namespaced:
// Ok((ref namespacevalue, Event::Start(ref e)))
match e.name() {
b"tag1" => println!("attributes values: {:?}",
e.attributes().map(|a| a.unwrap().value).collect::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();
} ```
```rust use quickxml::writer::Writer; use quickxml::reader::Reader; use quick_xml::events::{Event, BytesEnd, BytesStart}; use std::io::Cursor; use std::iter;
let xml = r#"
// crates a new element ... alternatively we could reuse `e` by calling
// `e.into_owned()`
let mut elem = BytesStart::owned(b"my_elem".to_vec(), "my_elem".len());
// collect existing attributes
elem.extend_attributes(e.attributes().map(|attr| attr.unwrap()));
// copy existing attributes, adds a new my-key="some value" attribute
elem.push_attribute(("my-key", "some value"));
// writes the event to the writer
assert!(writer.write_event(Event::Start(elem)).is_ok());
},
Ok(Event::End(ref e)) if e.name() == b"this_tag" => {
assert!(writer.write_event(Event::End(BytesEnd::borrowed(b"my_elem"))).is_ok());
},
Ok(Event::Eof) => break,
Ok(e) => assert!(writer.write_event(e).is_ok()),
// or using the buffer
// Ok(e) => assert!(writer.write(&buf).is_ok()),
Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
}
buf.clear();
}
let result = writer.intoinner().intoinner();
let expected = r#"
quick-xml is 40+ times faster than the widely used xml-rs crate.
``` // quick-xml benches test benchquickxml ... bench: 316,915 ns/iter (+/- 59,750) test benchquickxmlescaped ... bench: 430,226 ns/iter (+/- 19,036) test benchquickxmlnamespaced ... bench: 452,997 ns/iter (+/- 30,077) test benchquickxml_wrapper ... bench: 313,846 ns/iter (+/- 93,794)
// same bench with xml-rs test benchxmlrs ... bench: 15,329,068 ns/iter (+/- 3,966,413) ```
Any PR is welcomed!
MIT