Struct quick_xml::Reader[][src]

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

A low level encoding-agnostic XML event reader.

Consumes a BufRead and streams XML Events.

Examples

use quick_xml::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 that reads from a reader implementing BufRead.

Changes whether empty elements should be split into an Open and a Close event.

When set to true, all Empty events produced by a self-closing tag like <tag/> are expanded into a Start event followed by a End event. When set to false (the default), those tags are represented by an Empty event instead.

(false by default)

Changes whether whitespace before and after character data should be removed.

When set to true, all Text events are trimmed. If they are empty, no event will be pushed.

(false by default)

Changes whether mismatched closing tag names should be detected.

When set to false, it won't check if a closing tag matches the corresponding opening tag. For example, <mytag></different_tag> will be permitted.

If the XML is known to be sane (already processed, etc.) this saves extra time.

Note that the emitted End event will not be modified if this is disabled, ie. it will contain the data of the mismatched end tag.

(true by default)

Changes whether comments should be validated.

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

(false by default)

Gets the current byte position in the input data.

Useful when debugging errors.

Reads the next Event.

This is the main entry point for reading XML Events.

Events borrow buf and can be converted to own their data 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 constrained 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;
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 resolves its namespace (if applicable).

Examples

use std::str::from_utf8;
use quick_xml::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.

This encoding will be used by decode.

Decodes a slice using the encoding specified in the XML declaration.

Decode bytes with BOM sniffing and with malformed sequences replaced with the U+FFFD REPLACEMENT CHARACTER.

If no encoding is specified, defaults to UTF-8.

Reads until end element is found

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

Reads optional text between start and end tags.

If the next event is a Text event, returns the decoded and unescaped content as a String. If the next event is an End event, returns the empty string. In all other cases, returns an error.

Any text will be decoded using the XML encoding specified in the XML declaration (or UTF-8 if none is specified).

Examples

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

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

let expected = ["<b>", ""];
for &content in expected.iter() {
    match xml.read_event(&mut Vec::new()) {
        Ok(Event::Start(ref e)) => {
            assert_eq!(&xml.read_text(e.name(), &mut Vec::new()).unwrap(), content);
        },
        e => panic!("Expecting Start event, found {:?}", e),
    }
}

impl Reader<BufReader<File>>
[src]

Creates an XML reader from a file path.

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

Creates an XML reader from a string slice.

Auto Trait Implementations

impl<B> Send for Reader<B> where
    B: Send

impl<B> Sync for Reader<B> where
    B: Sync