Skip to main content

SerializerConfig

Struct SerializerConfig 

Source
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 &amp; 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

Source

pub const fn new() -> SerializerConfig

Creates the default configuration.

Source

pub const fn builder() -> SerializerConfigBuilder

Returns a builder for the configuration (see SerializerConfigBuilder).

Source

pub const fn into_builder(self) -> SerializerConfigBuilder

Returns a builder that starts with this configuration.

Source

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.

Source

pub fn context(&self) -> &Context

Returns the context the values are serialized in.

Source

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.

Source

pub const fn set_attribute_prefix(&mut self, prefix: &'static str)

Sets the prefix of the keys that are attributes (default @).

Source

pub const fn set_text_key(&mut self, key: &'static str)

Sets the key that is the text of an element (default $text).

Source

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>"
);
Source

pub const fn set_declaration(&mut self, yes: bool)

Sets if the XML declaration is written (default false).

Source

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 has Layout::Expanded).
  • Mixed keeps whitespace as text by default, its content is written on a single line.
  • Elements and sequences with Layout::Compact (see hints) 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.

Source

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

pub fn to_string<T: Serialize + ?Sized>( &self, value: &T, ) -> Result<String, Error>

Serializes a value.

Source

pub fn to_string_with<F, T: Serialize + ?Sized>( &self, value: &T, 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

Source

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>"
);
Source

pub fn to_writer<W: Write, T: Serialize + ?Sized>( &self, writer: W, value: &T, ) -> Result<(), Error>

Serializes a value as XML document to a writer.

See to_writer.

Trait Implementations§

Source§

impl Clone for SerializerConfig

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for SerializerConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for SerializerConfig

Source§

fn default() -> SerializerConfig

Returns the “default value” for a type. Read more
Source§

impl Eq for SerializerConfig

Source§

impl PartialEq for SerializerConfig

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for SerializerConfig

Auto Trait Implementations§

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

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

fn clone_into(&self, target: &mut T)

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

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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.