Struct quick_xml::reader::Reader [] [src]

pub struct Reader<B: BufRead> { /* fields omitted */ }

A low level Xml bytes reader

Consumes a BufRead and streams xml Events

use quick_xml::reader::Reader;
use quick_xml::events::Event;

let xml = r#"<tag1 att1 = "test">
                <tag2><!--Test comment-->Test</tag2>
                <tag2>Test 2</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();
loop {
    match reader.read_event(&mut buf) {
        Ok(Event::Start(ref e)) => {
            match e.name() {
                b"tag1" => println!("attributes values: {:?}",
                                    e.attributes().map(|a| a.unwrap().value)
                                    .collect::<Vec<_>>()),
                b"tag2" => count += 1,
                _ => (),
            }
        },
        Ok(Event::Text(e)) => txt.push(e.unescape_and_decode(&reader).unwrap()),
        Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
        Ok(Event::Eof) => break,
        _ => (),
    }
    buf.clear();
}

Methods

impl<B: BufRead> Reader<B>
[src]

Creates a Reader from a generic BufReader

Change expand_empty_elements default behaviour (true per default)

When set to true, all Empty events are expanded into an Open event followed by a Close Event.

Change trim_text default behaviour (false per default)

When set to true, all Text events are trimed. If they are empty, no event if pushed

Change default check_end_names (true per default)

When set to false, it won't check if End node match last Start node. If the xml is known to be sane (already processed etc ...) this saves extra time

Change default check_comment (false per default)

When set to true, every Comment event will be checked for not containing -- Most of the time we don't want comments at all so we don't really care about comment correctness, thus default value is false for performance reason

Gets the current BufRead position Useful when debugging errors

reads the next Event

This is the main entry for reading xml Events.

Events borrow buf and can get the ownership if needed (uses Cow internally).

Having the possibility to control the internal buffers gives you some additional benefits such as: - reduce the number of allocations by reusing the same buffer. For contrained systems, you can call buf.clear() once you are done with processing the event (typically at the end of your loop) - reserve the buffer length if you know the file size (using Vec::with_capacity)

Examples

use quick_xml::reader::Reader;
use quick_xml::events::Event;

let xml = r#"<tag1 att1 = "test">
                <tag2><!--Test comment-->Test</tag2>
                <tag2>Test 2</tag2>
            </tag1>"#;
let mut reader = Reader::from_str(xml);
reader.trim_text(true);
let mut count = 0;
let mut buf = Vec::new();
let mut txt = Vec::new();
loop {
    match reader.read_event(&mut buf) {
        Ok(Event::Start(ref e)) => count += 1,
        Ok(Event::Text(e)) => txt.push(e.unescape_and_decode(&reader).expect("Error!")),
        Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
        Ok(Event::Eof) => break,
        _ => (),
    }
    buf.clear();
}
println!("Found {} start events", count);
println!("Text events: {:?}", txt);

Resolves a potentially qualified attribute name into (namespace name, local name).

Qualified attribute names have the form prefix:local-name where theprefix is defined on any containing XML element via xmlns:prefix="the:namespace:uri". The namespace prefix can be defined on the same element as the attribute in question.

Unqualified attribute names do not inherit the current default namespace.

Reads the next event and resolve its namespace

Examples

use std::str::from_utf8;
use quick_xml::reader::Reader;
use quick_xml::events::Event;

let xml = r#"<x:tag1 xmlns:x="www.xxxx" xmlns:y="www.yyyy" att1 = "test">
                <y:tag2><!--Test comment-->Test</y:tag2>
                <y:tag2>Test 2</y:tag2>
            </x:tag1>"#;
let mut reader = Reader::from_str(xml);
reader.trim_text(true);
let mut count = 0;
let mut buf = Vec::new();
let mut ns_buf = Vec::new();
let mut txt = Vec::new();
loop {
    match reader.read_namespaced_event(&mut buf, &mut ns_buf) {
        Ok((ref ns, Event::Start(ref e))) => {
            count += 1;
            match (*ns, e.local_name()) {
                (Some(b"www.xxxx"), b"tag1") => (),
                (Some(b"www.yyyy"), b"tag2") => (),
                (ns, n) => panic!("Namespace and local name mismatch"),
            }
            println!("Resolved namespace: {:?}", ns.and_then(|ns| from_utf8(ns).ok()));
        }
        Ok((_, Event::Text(e))) => {
            txt.push(e.unescape_and_decode(&reader).expect("Error!"))
        },
        Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
        Ok((_, Event::Eof)) => break,
        _ => (),
    }
    buf.clear();
}
println!("Found {} start events", count);
println!("Text events: {:?}", txt);

Returns the Readers encoding

The used encoding may change after parsing the xml declaration

Decodes a slice using the xml specified encoding

Decode complete input to Cow<'a, str> with BOM sniffing and with malformed sequences replaced with the REPLACEMENT CHARACTER

If no encoding is specified, then defaults to UTF_8

Reads until end element is found

Manages nested cases where parent and child elements have the same name

Reads next event, if Event::Text or Event::End, then returns an unescaped String, else returns an error

Examples

use quick_xml::reader::Reader;
use quick_xml::events::Event;

let mut xml = Reader::from_reader(b"<a>&lt;b&gt;</a>" as &[u8]);

xml.trim_text(true);
let mut buf = Vec::new();

match xml.read_event(&mut buf) {
    Ok(Event::Start(ref e)) => {
        assert_eq!(&xml.read_text(e.name(), &mut Vec::new()).unwrap(), "<b>");
    },
    e => panic!("Expecting Start(a), found {:?}", e),
}

impl Reader<BufReader<File>>
[src]

Creates a xml reader from a file path

impl<'a> Reader<&'a [u8]>
[src]

Creates a xml reader from a file path