pub struct Writer<W> { /* private fields */ }Expand description
XML writer. Writes XML Events to a std::io::Write implementor.
§Examples
This example reads an XML document event by event, renaming one element while keeping the rest verbatim, and writes it back out.
use oxixml_xml::events::{BytesEnd, BytesStart, Event};
use oxixml_xml::reader::Reader;
use oxixml_xml::writer::Writer;
let xml = r#"<this_tag k1="v1" k2="v2"><child>text</child></this_tag>"#;
let mut reader = Reader::from_str(xml);
let mut writer = Writer::new(Vec::new());
loop {
match reader.read_event().expect("valid event") {
Event::Start(e) if e.name().as_ref() == b"this_tag" => {
let mut elem = BytesStart::new("my_elem");
elem.extend_attributes(e.attributes().map(|attr| attr.expect("attr")));
elem.push_attribute(("my-key", "some value"));
writer.write_event(Event::Start(elem)).expect("start");
}
Event::End(e) if e.name().as_ref() == b"this_tag" => {
writer.write_event(Event::End(BytesEnd::new("my_elem"))).expect("end");
}
Event::Eof => break,
e => writer.write_event(e).expect("event"),
}
}
let result = writer.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§
Source§impl<W: AsyncWrite + Unpin> Writer<W>
impl<W: AsyncWrite + Unpin> Writer<W>
Sourcepub async fn write_event_async<'a, E: Into<Event<'a>>>(
&mut self,
event: E,
) -> Result<()>
Available on crate feature async-tokio only.
pub async fn write_event_async<'a, E: Into<Event<'a>>>( &mut self, event: E, ) -> Result<()>
async-tokio only.Writes the given event to the underlying writer. Async version of
Writer::write_event.
Sourcepub async fn write_indent_async(&mut self) -> Result<()>
Available on crate feature async-tokio only.
pub async fn write_indent_async(&mut self) -> Result<()>
async-tokio only.Manually writes a newline and indentation at the proper level. Async
version of Writer::write_indent.
This method does nothing if Writer was not constructed with
Writer::new_with_indent.
Source§impl<W> Writer<W>
impl<W> Writer<W>
Sourcepub fn new_with_indent(
inner: W,
indent_char: u8,
indent_size: usize,
) -> Writer<W>
pub fn new_with_indent( inner: W, indent_char: u8, indent_size: usize, ) -> Writer<W>
Creates a Writer with configured indentation from a generic writer.
Each nesting level is indented by indent_size repetitions of the
indent_char byte (typically b' ' or b'\t').
Sourcepub fn into_inner(self) -> W
pub fn into_inner(self) -> W
Consumes this Writer, returning the underlying writer.
Sourcepub fn config_mut(&mut self) -> &mut Config
pub fn config_mut(&mut self) -> &mut Config
Returns a mutable reference to the writer configuration.
Sourcepub fn create_element<'a, N>(&'a mut self, name: N) -> ElementWriter<'a, W>
pub fn create_element<'a, N>(&'a mut self, name: N) -> ElementWriter<'a, W>
Provides a simple, high-level API for writing an XML element.
Returns an ElementWriter that simplifies setting attributes and writing
content inside the element.
§Example
use oxixml_xml::events::BytesText;
use oxixml_xml::writer::Writer;
let mut writer = Writer::new(Vec::new());
// writes <tag attr1="value1"/>
writer.create_element("tag")
.with_attribute(("attr1", "value1"))
.write_empty()
.expect("empty");
// writes <tag attr1="value1" attr2="value2">with some text inside</tag>
writer.create_element("tag")
.with_attributes(vec![("attr1", "value1"), ("attr2", "value2")])
.write_text_content(BytesText::new("with some text inside"))
.expect("text");
// 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::new(item))?;
}
Ok(())
})
.expect("inner");Source§impl<W: Write> Writer<W>
impl<W: Write> Writer<W>
Sourcepub fn write_bom(&mut self) -> Result<()>
pub fn write_bom(&mut self) -> Result<()>
Writes a Byte-Order-Mark character to the document.
§Example
use oxixml_xml::writer::Writer;
let mut writer = Writer::new_with_indent(Vec::new(), b' ', 4);
writer.write_bom().expect("bom");
writer
.create_element("empty")
.with_attribute(("attr1", "value1"))
.write_empty()
.expect("empty");
assert_eq!(
std::str::from_utf8(&writer.into_inner()).expect("utf-8"),
"\u{FEFF}<empty attr1=\"value1\"/>"
);Sourcepub fn write_event<'a, E: Into<Event<'a>>>(&mut self, event: E) -> Result<()>
pub fn write_event<'a, E: Into<Event<'a>>>(&mut self, event: E) -> Result<()>
Writes the given event to the underlying writer.
Sourcepub fn write_indent(&mut self) -> Result<()>
pub fn write_indent(&mut self) -> Result<()>
Manually writes a newline and indentation at the proper level.
This can be used when the heuristic to line break and indent after every
Event apart from Text fails, such as when a
Start occurs directly after a Text.
This method does nothing if Writer was not constructed with
new_with_indent.
Sourcepub fn write_serializable<T: Serialize>(
&mut self,
tag_name: &str,
content: &T,
) -> Result<(), SeError>
Available on crate feature serialize only.
pub fn write_serializable<T: Serialize>( &mut self, tag_name: &str, content: &T, ) -> Result<(), SeError>
serialize only.Writes a serde-serializable value as an XML element named tag_name.
The value is serialized with crate::se::Serializer, so the usual
mapping rules apply (@field becomes an attribute, $text becomes the
text content, and so on). If this Writer was created with
new_with_indent, the produced markup shares the
writer’s indentation state.
§Examples
#[derive(Debug, PartialEq, Serialize)]
struct MyData {
question: String,
answer: u32,
}
let data = MyData {
question: "The Ultimate Question of Life, the Universe, and Everything".into(),
answer: 42,
};
let mut buffer = Vec::new();
let mut writer = Writer::new_with_indent(&mut buffer, b' ', 4);
let start = BytesStart::new("root");
let end = start.to_end();
writer.write_event(Event::Start(start.clone()))?;
writer.write_serializable("my_data", &data)?;
writer.write_event(Event::End(end))?;
assert_eq!(
std::str::from_utf8(&buffer)?,
r#"<root>
<my_data>
<question>The Ultimate Question of Life, the Universe, and Everything</question>
<answer>42</answer>
</my_data>
</root>"#
);