Module quick_xml::serde_helpers::text_content
source · Available on crate feature
serde-types
only.Expand description
Provides helper functions to serialization and deserialization of types
(usually enums) as a text content of an element and intended to use with
#[serde(with = "...")]
, #[serde(deserialize_with = "...")]
and #[serde(serialize_with = "...")]
.
When you serialize unit variants of enums, they are serialized as an empty
element, like <Unit/>
. If your enum consist only of unit variants,
it is frequently required to serialize them as string content of an
element, like <field>Unit</field>
. To make this possible use this module.
use quick_xml::de::from_str;
use quick_xml::se::to_string;
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, PartialEq, Debug)]
enum SomeEnum {
// Default implementation serializes enum as an `<EnumValue/>` element
EnumValue,
...
}
#[derive(Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename = "some-container")]
struct SomeContainer {
#[serde(with = "quick_xml::serde_helpers::text_content")]
field: SomeEnum,
}
let container = SomeContainer {
field: SomeEnum::EnumValue,
};
let xml = "\
<some-container>\
<field>EnumValue</field>\
</some-container>";
assert_eq!(to_string(&container).unwrap(), xml);
assert_eq!(from_str::<SomeContainer>(xml).unwrap(), container);
Using of this module is equivalent to replacing field
’s type to this:
#[derive(Serialize, Deserialize)]
struct Field {
// Use a special name `$text` to map field to the text content
#[serde(rename = "$text")]
content: SomeEnum,
}
#[derive(Serialize, Deserialize)]
#[serde(rename = "some-container")]
struct SomeContainer {
field: Field,
}
Read about the meaning of a special $text
field.
Functions
- Deserializes XSD’s simple type. Intended to use with
#[serde(deserialize_with = "...")]
. See example attext_content
module level. - Serializes
value
as an XSD simple type. Intended to use with#[serde(serialize_with = "...")]
. See example attext_content
module level.