quick-xml icon indicating copy to clipboard operation
quick-xml copied to clipboard

Write comment when using serde serialization?

Open sydhds opened this issue 1 year ago • 1 comments

Is there a way to add comments when using quick_xml serde serialization? I've tried to implement something like:

#[derive(Debug, PartialEq, Default, Deserialize)]
struct XbelHighestId(u64);

pub fn serialize_highest_id<S>(
    highest_id: &XbelHighestId,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let comment = format!(r#"<!--- highestId :{}: -->"#, highest_id.0);
    serializer.serialize_str(&comment)
}

struct Xbel {
    [...]
    #[serde(serialize_with = "serialize_highest_id", rename = "$text")]
    highest_id: XbelHighestId,
}

but serialize_str transform '<' & '>' character into their xml equivalent...

sydhds avatar Sep 30 '24 14:09 sydhds

Currently that is impossible by design. Serde has no "comment" fields in their data model, so no any serializer is able to write comments from the data structs (of course, serializers can write comments, but their will not be data-driven). The only workaround is to create a special type that, when serialized, will write comment and teach each serializer that it should serialize that type in a special manner. The similar approach is used by the serde-spanned, but for deserialization.

It seems to me, that that special type should live in a separate crate, and if one will exist, I'm not against a PR that will add a support of that crate to quick-xml.

Mingun avatar Sep 30 '24 15:09 Mingun