tafia / quick-xml

Rust high performance xml reader and writer
MIT License
1.18k stars 235 forks source link

Write comment when using serde serialization? #812

Open sydhds opened 19 hours ago

sydhds commented 19 hours ago

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...

Mingun commented 18 hours ago

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.