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 set_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, set_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 builder() -> SerializerConfigBuilder
pub const fn builder() -> SerializerConfigBuilder
Returns a builder for the configuration (see SerializerConfigBuilder).
Sourcepub const fn into_builder(self) -> SerializerConfigBuilder
pub const fn into_builder(self) -> SerializerConfigBuilder
Returns a builder that starts with this configuration.
Sourcepub fn set_context(&mut self, context: Context)
pub fn set_context(&mut self, context: Context)
Sets the context the values are serialized in.
The values of the context are the defaults of the extension values
of the state (see Context), for instance
the BytesFormat. The serializers and
writers created with the configuration use this context. A context set on
the driver takes precedence.
Sourcepub const fn set_root(&mut self, name: &'static str)
pub const fn set_root(&mut self, name: &'static str)
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 set_attribute_prefix(&mut self, prefix: &'static str)
pub const fn set_attribute_prefix(&mut self, prefix: &'static str)
Sets the prefix of the keys that are attributes (default @).
Sourcepub const fn set_text_key(&mut self, key: &'static str)
pub const fn set_text_key(&mut self, key: &'static str)
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 set_declaration(&mut self, yes: bool)
pub const fn set_declaration(&mut self, yes: bool)
Sets if the XML declaration is written (default false).
Sourcepub const fn set_indent(&mut self, indent: Indent)
pub const fn set_indent(&mut self, indent: Indent)
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::builder().indent(Indent::Spaces(2)).build();
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 set_pretty(&mut self, indent: Indent)
pub const fn set_pretty(&mut self, indent: Indent)
Enables or disables pretty printing.
This is the same as set_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::builder().root("r").pretty(Indent::Tab).build();
assert_eq!(
PRETTY.to_string(&value).unwrap(),
"<r>\n\t<a>1</a>\n\t<b>2</b>\n</r>"
);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>"
);