pub struct SerializerConfig { /* private fields */ }Expand description
Configures how values are serialized to XML.
The value becomes the root element. Its name is the one of the
Root of the value (or of the document the value was
read from, if it’s a value that keeps event data like a
Recording), the name of the struct (or
enum) that is serialized or the configured root. Maps
are elements: keys with the
attribute prefix are attributes, the
text key is text and all other keys are child
elements. Sequences are elements with the same name, one per value.
Null values are left out. Attributes can come after other keys, they
are still written into the start tag.
Names can be {uri}local (the notation of James Clark, attributes are
@{uri}local, see qname!): their namespace gets the
configured prefix or a generated one (ns0, …).
Every namespace has one prefix in the document, all of them are
declared on the root element. Other names are written as they are.
#[derive(deser::Serialize)]
struct Link {
#[deser(rename = "@href")]
href: String,
#[deser(rename = "$text")]
title: String,
}
#[derive(deser::Serialize)]
#[deser(rename = "feed")]
struct Feed {
link: Vec<Link>,
updated: Option<String>,
}
let feed = Feed {
link: vec![Link { href: "/a".into(), title: "A & B".into() }],
updated: None,
};
assert_eq!(
deser_xml::to_string(&feed).unwrap(),
r#"<feed><link href="/a">A & B</link></feed>"#
);By default the output is a single line, indent writes
child elements on lines of their own.
Implementations§
Source§impl SerializerConfig
impl SerializerConfig
Sourcepub const fn new() -> SerializerConfig
pub const fn new() -> SerializerConfig
Creates the default configuration.
Sourcepub const fn root(self, name: &'static str) -> SerializerConfig
pub const fn root(self, name: &'static str) -> SerializerConfig
Sets the name of the root element of values without a name.
The root element is named after the Root of the
value or the struct or enum that is serialized. Other values (like
maps) are named with this. This is useful where values cannot be
wrapped in a Root, for instance when transcoding from another
format.
Sourcepub const fn attribute_prefix(self, prefix: &'static str) -> SerializerConfig
pub const fn attribute_prefix(self, prefix: &'static str) -> SerializerConfig
Sets the prefix of the keys that are attributes (default @).
Sourcepub const fn text_key(self, key: &'static str) -> SerializerConfig
pub const fn text_key(self, key: &'static str) -> SerializerConfig
Sets the key that is the text of an element (default $text).
Sourcepub const fn namespaces(
self,
namespaces: &'static [(&'static str, &'static str)],
) -> SerializerConfig
pub const fn namespaces( self, namespaces: &'static [(&'static str, &'static str)], ) -> SerializerConfig
Sets the prefixes of namespaces that are declared on the root element.
The namespaces of the Root of the value come first,
configured namespaces whose prefix they use are left out. The empty
prefix declares the default namespace. Names that are
{uri}local are written with these prefixes, attributes only with
prefixes that are not empty. Namespaces without prefix get
generated ones. The table can be written with
prefixes!.
use deser_xml::SerializerConfig;
deser_xml::namespace!(
atom = "http://www.w3.org/2005/Atom",
dc = "http://purl.org/dc/elements/1.1/",
media = "http://search.yahoo.com/mrss/",
);
#[derive(deser::Serialize)]
#[deser(rename = atom!("feed"))]
struct Feed {
#[deser(rename = atom!("title"))]
title: String,
#[deser(rename = dc!("creator"))]
creator: Vec<String>,
#[deser(rename = media!("thumbnail"))]
thumbnail: String,
}
const CONFIG: SerializerConfig = SerializerConfig::new()
.namespaces(deser_xml::prefixes![atom as "", dc]);
let feed = Feed {
title: "x".into(),
creator: vec!["y".into(), "z".into()],
thumbnail: "t.png".into(),
};
assert_eq!(
CONFIG.to_string(&feed).unwrap(),
"<feed xmlns=\"http://www.w3.org/2005/Atom\" \
xmlns:dc=\"http://purl.org/dc/elements/1.1/\" \
xmlns:ns0=\"http://search.yahoo.com/mrss/\"><title>x</title>\
<dc:creator>y</dc:creator><dc:creator>z</dc:creator>\
<ns0:thumbnail>t.png</ns0:thumbnail></feed>"
);Sourcepub const fn declaration(self, yes: bool) -> SerializerConfig
pub const fn declaration(self, yes: bool) -> SerializerConfig
Sets if the XML declaration is written (default false).
Sourcepub const fn indent(self, indent: Indent) -> SerializerConfig
pub const fn indent(self, indent: Indent) -> SerializerConfig
Sets how the output is indented.
By default (Indent::None) the document is written on a single
line. Otherwise the child elements of an element are written on
lines of their own, indented by their depth, and the end tag on a
line of its own:
use deser_xml::{Indent, SerializerConfig};
#[derive(deser::Serialize)]
#[deser(rename = "point")]
struct Point {
#[deser(rename = "@id")]
id: u32,
x: i32,
y: i32,
}
const PRETTY: SerializerConfig =
SerializerConfig::new().indent(Indent::Spaces(2));
assert_eq!(
PRETTY.to_string(&Point { id: 1, x: 3, y: 4 }).unwrap(),
"<point id=\"1\">\n <x>3</x>\n <y>4</y>\n</point>"
);Unlike in JSON whitespace can be text in XML. It is only added between tags where it’s not text of the elements (the deserializer skips it), elements with text are written on a single line:
- The text of elements is never changed, elements with text and
child elements (mixed content like
<p>x <b>y</b></p>) are written on a single line from the text on. If the element is a struct whose text key field comes after the child element, the element is written on a single line from the start (unless it hasLayout::Expanded). Mixedkeeps whitespace as text by default, its content is written on a single line.- Elements and sequences with
Layout::Compact(seehints) are written on a single line, also their content.
With the declaration the root element starts on a new line. The output never ends with a line break.
Sourcepub const fn pretty(self, indent: Indent) -> SerializerConfig
pub const fn pretty(self, indent: Indent) -> SerializerConfig
Enables or disables pretty printing.
This is the same as indent, XML has no spaces
after separators like JSON.
use std::collections::BTreeMap;
use deser_xml::{Indent, SerializerConfig};
let value = BTreeMap::from([("a", 1), ("b", 2)]);
const PRETTY: SerializerConfig =
SerializerConfig::new().root("r").pretty(Indent::Tab);
assert_eq!(
PRETTY.to_string(&value).unwrap(),
"<r>\n\t<a>1</a>\n\t<b>2</b>\n</r>"
);Sourcepub const fn bytes(self, format: BytesFormat) -> SerializerConfig
pub const fn bytes(self, format: BytesFormat) -> SerializerConfig
Sets how bytes are written (default base64).
Sourcepub fn to_string_with<F>(
&self,
value: &dyn Serialize,
setup: F,
) -> Result<String, Error>where
F: FnOnce(&mut SerializeDriver<'_>),
pub fn to_string_with<F>(
&self,
value: &dyn Serialize,
setup: F,
) -> Result<String, Error>where
F: FnOnce(&mut SerializeDriver<'_>),
Serializes a value with a configured driver.
The callback is invoked with the driver before the serialization
starts, for instance to add Layers.
Source§impl SerializerConfig
impl SerializerConfig
Sourcepub fn writer<W: Write>(&self, writer: W) -> Writer<W, Serializer>
pub fn writer<W: Write>(&self, writer: W) -> Writer<W, Serializer>
Creates a writer of an XML document (see
deser::io::Writer).
A stream holds a single document, writing a second value fails. The
document is written in parts while the value is serialized (see
Serializer).
use deser_xml::SerializerConfig;
#[derive(deser::Serialize)]
#[deser(rename = "feed")]
struct Feed {
entry: Vec<u32>,
}
let mut writer = SerializerConfig::new().writer(Vec::new());
writer.set_buffer_limit(8);
writer.write(&Feed { entry: vec![1, 2, 3] }).unwrap();
assert_eq!(
writer.into_inner(),
b"<feed><entry>1</entry><entry>2</entry><entry>3</entry></feed>"
);