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 = "...")]
.
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.
In versions of quick-xml before 0.31.0 this module used to represent enum
unit variants as <field>EnumUnitVariant</field>
instead of <EnumUnitVariant/>
.
Since version 0.31.0 this is default representation of enums in normal fields,
and <EnumUnitVariant/>
requires $value
field:
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(rename = "$value")]
field: SomeEnum,
}
let container = SomeContainer {
field: SomeEnum::EnumValue,
};
let xml = "\
<some-container>\
<EnumValue/>\
</some-container>";
assert_eq!(to_string(&container).unwrap(), xml);
assert_eq!(from_str::<SomeContainer>(xml).unwrap(), container);
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.