Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Write comment when using serde serialization? #812

Open
sydhds opened this issue Sep 30, 2024 · 1 comment
Open

Write comment when using serde serialization? #812

sydhds opened this issue Sep 30, 2024 · 1 comment
Labels
question serde Issues related to mapping from Rust types to XML

Comments

@sydhds
Copy link

sydhds commented Sep 30, 2024

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 Mingun added question serde Issues related to mapping from Rust types to XML labels Sep 30, 2024
@Mingun
Copy link
Collaborator

Mingun commented Sep 30, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question serde Issues related to mapping from Rust types to XML
Projects
None yet
Development

No branches or pull requests

2 participants