quick_xml::writer

Struct ElementWriter

Source
pub struct ElementWriter<'a, W> { /* private fields */ }
Expand description

A struct to write an element. Contains methods to add attributes and inner elements to the element

Implementations§

Source§

impl<'a, W: AsyncWrite + Unpin> ElementWriter<'a, W>

Source

pub async fn write_text_content_async( self, text: BytesText<'_>, ) -> Result<&'a mut Writer<W>>

Available on crate feature async-tokio only.

Write some text inside the current element.

§Example
let mut buffer = Vec::new();
let mut tokio_buffer = tokio::io::BufWriter::new(&mut buffer);
let mut writer = Writer::new_with_indent(&mut tokio_buffer, b' ', 4);

writer
    .create_element("paired")
    .with_attribute(("attr1", "value1"))
    .with_attribute(("attr2", "value2"))
    .write_text_content_async(BytesText::new("text"))
    .await
    .expect("cannot write content");

tokio_buffer.flush().await.expect("flush failed");

assert_eq!(
    std::str::from_utf8(&buffer).unwrap(),
    r#"<paired attr1="value1" attr2="value2">text</paired>"#
);
Source

pub async fn write_cdata_content_async( self, text: BytesCData<'_>, ) -> Result<&'a mut Writer<W>>

Available on crate feature async-tokio only.

Write a CData event <![CDATA[...]]> inside the current element.

§Example
let mut buffer = Vec::new();
let mut tokio_buffer = tokio::io::BufWriter::new(&mut buffer);
let mut writer = Writer::new_with_indent(&mut tokio_buffer, b' ', 4);

writer
    .create_element("paired")
    .with_attribute(("attr1", "value1"))
    .with_attribute(("attr2", "value2"))
    .write_cdata_content_async(BytesCData::new("text & content"))
    .await
    .expect("cannot write content");

tokio_buffer.flush().await.expect("flush failed");

assert_eq!(
    std::str::from_utf8(&buffer).unwrap(),
    r#"<paired attr1="value1" attr2="value2"><![CDATA[text & content]]></paired>"#
);
Source

pub async fn write_pi_content_async( self, text: BytesPI<'_>, ) -> Result<&'a mut Writer<W>>

Available on crate feature async-tokio only.

Write a processing instruction <?...?> inside the current element.

§Example
let mut buffer = Vec::new();
let mut tokio_buffer = tokio::io::BufWriter::new(&mut buffer);
let mut writer = Writer::new_with_indent(&mut tokio_buffer, b' ', 4);

writer
    .create_element("paired")
    .with_attribute(("attr1", "value1"))
    .with_attribute(("attr2", "value2"))
    .write_pi_content_async(BytesPI::new(r#"xml-stylesheet href="style.css""#))
    .await
    .expect("cannot write content");

tokio_buffer.flush().await.expect("flush failed");

assert_eq!(
    std::str::from_utf8(&buffer).unwrap(),
    r#"<paired attr1="value1" attr2="value2">
    <?xml-stylesheet href="style.css"?>
</paired>"#
);
Source

pub async fn write_empty_async(self) -> Result<&'a mut Writer<W>>

Available on crate feature async-tokio only.

Write an empty (self-closing) tag.

§Example
let mut buffer = Vec::new();
let mut tokio_buffer = tokio::io::BufWriter::new(&mut buffer);
let mut writer = Writer::new_with_indent(&mut tokio_buffer, b' ', 4);

writer
    .create_element("empty")
    .with_attribute(("attr1", "value1"))
    .with_attribute(("attr2", "value2"))
    .write_empty_async()
    .await
    .expect("cannot write content");

tokio_buffer.flush().await.expect("flush failed");

assert_eq!(
    std::str::from_utf8(&buffer).unwrap(),
    r#"<empty attr1="value1" attr2="value2"/>"#
);
Source

pub async fn write_inner_content_async<F, Fut, E>( self, closure: F, ) -> StdResult<&'a mut Writer<W>, E>
where F: FnOnce(&'a mut Writer<W>) -> Fut, Fut: Future<Output = StdResult<&'a mut Writer<W>, E>>, E: From<Error>,

Available on crate feature async-tokio only.

Create a new scope for writing XML inside the current element.

§Example
use quick_xml::Error;

let mut buffer = Vec::new();
let mut tokio_buffer = tokio::io::BufWriter::new(&mut buffer);
let mut writer = Writer::new_with_indent(&mut tokio_buffer, b' ', 4);

writer
    .create_element("outer")
    .with_attributes([("attr1", "value1"), ("attr2", "value2")])
    // We need to provide error type, because it is not named somewhere explicitly
    .write_inner_content_async::<_, _, Error>(|writer| async move {
        let fruits = ["apple", "orange", "banana"];
        for (quant, item) in fruits.iter().enumerate() {
            writer
                .create_element("fruit")
                .with_attributes([("quantity", quant.to_string().as_str())])
                .write_text_content_async(BytesText::new(item))
                .await?;
        }
        writer
            .create_element("inner")
            .write_inner_content_async(|writer| async move {
                writer.create_element("empty").write_empty_async().await
            })
            .await?;

        Ok(writer)
    })
    .await
    .expect("cannot write content");

tokio_buffer.flush().await.expect("flush failed");
assert_eq!(
    std::str::from_utf8(&buffer).unwrap(),
    r#"<outer attr1="value1" attr2="value2">
    <fruit quantity="0">apple</fruit>
    <fruit quantity="1">orange</fruit>
    <fruit quantity="2">banana</fruit>
    <inner>
        <empty/>
    </inner>
</outer>"#
);
Source§

impl<'a, W> ElementWriter<'a, W>

Source

pub fn with_attribute<'b, I>(self, attr: I) -> Self
where I: Into<Attribute<'b>>,

Adds an attribute to this element.

Source

pub fn with_attributes<'b, I>(self, attributes: I) -> Self
where I: IntoIterator, I::Item: Into<Attribute<'b>>,

Add additional attributes to this element using an iterator.

The yielded items must be convertible to Attribute using Into.

Source

pub fn new_line(self) -> Self

Push a new line inside an element between attributes. Note, that this method does nothing if Writer was created without indentation support.

§Examples

The following code

let mut buffer = Vec::new();
let mut writer = Writer::new_with_indent(&mut buffer, b' ', 2);
writer
  .create_element("element")
    //.new_line() (1)
    .with_attribute(("first", "1"))
    .with_attribute(("second", "2"))
    .new_line()
    .with_attributes([
        ("third", "3"),
        ("fourth", "4"),
    ])
    //.new_line() (2)
    .write_empty();

will produce the following XMLs:

<!-- result of the code above. Spaces always is used -->
<element first="1" second="2"
         third="3" fourth="4"/>

<!-- if uncomment only (1) - indent depends on indentation
     settings - 2 spaces here -->
<element
  first="1" second="2"
  third="3" fourth="4"/>

<!-- if uncomment only (2). Spaces always is used  -->
<element first="1" second="2"
         third="3" fourth="4"
/>
Source§

impl<'a, W: Write> ElementWriter<'a, W>

Source

pub fn write_text_content( self, text: BytesText<'_>, ) -> Result<&'a mut Writer<W>>

Write some text inside the current element.

Source

pub fn write_cdata_content( self, text: BytesCData<'_>, ) -> Result<&'a mut Writer<W>>

Write a CData event <![CDATA[...]]> inside the current element.

Source

pub fn write_pi_content(self, pi: BytesPI<'_>) -> Result<&'a mut Writer<W>>

Write a processing instruction <?...?> inside the current element.

Source

pub fn write_empty(self) -> Result<&'a mut Writer<W>>

Write an empty (self-closing) tag.

Source

pub fn write_inner_content<F>(self, closure: F) -> Result<&'a mut Writer<W>>
where F: FnOnce(&mut Writer<W>) -> Result<()>,

Create a new scope for writing XML inside the current element.

Auto Trait Implementations§

§

impl<'a, W> Freeze for ElementWriter<'a, W>

§

impl<'a, W> RefUnwindSafe for ElementWriter<'a, W>
where W: RefUnwindSafe,

§

impl<'a, W> Send for ElementWriter<'a, W>
where W: Send,

§

impl<'a, W> Sync for ElementWriter<'a, W>
where W: Sync,

§

impl<'a, W> Unpin for ElementWriter<'a, W>

§

impl<'a, W> !UnwindSafe for ElementWriter<'a, W>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.