pub struct Writer<W: Write> { /* private fields */ }
Expand description

XML writer.

Writes XML Events to a Write implementor.

Examples

use quick_xml::{Reader, Writer};
use quick_xml::events::{Event, BytesEnd, BytesStart};
use std::io::Cursor;

let xml = r#"<this_tag k1="v1" k2="v2"><child>text</child></this_tag>"#;
let mut reader = Reader::from_str(xml);
reader.trim_text(true);
let mut writer = Writer::new(Cursor::new(Vec::new()));
let mut buf = Vec::new();
loop {
    match reader.read_event(&mut buf) {
        Ok(Event::Start(ref e)) if e.name() == b"this_tag" => {

            // 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,
        // we can either move or borrow the event to write, depending on your use-case
        Ok(e) => assert!(writer.write_event(&e).is_ok()),
        Err(e) => panic!("{}", e),
    }
    buf.clear();
}

let result = writer.into_inner().into_inner();
let expected = r#"<my_elem k1="v1" k2="v2" my-key="some value"><child>text</child></my_elem>"#;
assert_eq!(result, expected.as_bytes());

Implementations

Creates a Writer from a generic Write

Creates a Writer with configured whitespace indents from a generic Write

Consumes this Writer, returning the underlying writer.

Get inner writer, keeping ownership

Writes the given event to the underlying writer.

Writes bytes

Manually write a newline and indentation at the proper level.

This can be used when the heuristic to line break and indent after any Event apart from Text fails such as when a Start occurs directly after Text. This method will do nothing if Writer was not constructed with new_with_indent.

Provides a simple, high-level API for writing XML elements.

Returns an ElementWriter that simplifies setting attributes and writing content inside the element.

Example
use quick_xml::{Error, Writer};
use quick_xml::events::{BytesStart, BytesText, Event};
use std::io::Cursor;

let mut writer = Writer::new(Cursor::new(Vec::new()));

// writes <tag attr1="value1"/>
writer.create_element("tag")
    .with_attribute(("attr1", "value1"))  // chain `with_attribute()` calls to add many attributes
    .write_empty()?;

// writes <tag attr1="value1" attr2="value2">with some text inside</tag>
writer.create_element("tag")
    .with_attributes(vec![("attr1", "value1"), ("attr2", "value2")].into_iter())  // or add attributes from an iterator
    .write_text_content(BytesText::from_plain_str("with some text inside"))?;

// writes <tag><fruit quantity="0">apple</fruit><fruit quantity="1">orange</fruit></tag>
writer.create_element("tag")
    .write_inner_content(|writer| {
        let fruits = ["apple", "orange"];
        for (quant, item) in fruits.iter().enumerate() {
            writer
                .create_element("fruit")
                .with_attribute(("quantity", quant.to_string().as_str()))
                .write_text_content(BytesText::from_plain_str(item))?;
        }
        Ok(())
    })?;

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.