Gmac
Gmac

Reputation: 21

How can I add an xml declaration when serializing data using quick_xml and serde?

I am trying to use the serde functionality of quick_xml to serialize and deserialize between xml and rust. A minimal example shown below works well. However when I serialize back into xml I no longer have the xml declaration, which makes sense as I don't have it as part of the rust struct.

#[derive(Default, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename = "response", default)]
pub struct Response {
    pub protocol: String,
    pub server: String,
}

Deserialisation from this:

<?xml version="1.0" encoding="UTF-8"?>
<response protocol="3.0" server="prod">
</response>

Serialisation looks like this:

<response protocol="3.0" server="prod">
</response>

My question is what is the best way to include the declaration when serializing back into xml. There seems to be an Event::Decl which handles this but I'm not sure of usage through serde. Should the declaration be a part of my Rust structure or could I leave it out and handle it seperately?

Upvotes: 1

Views: 883

Answers (1)

Nazar Antoniuk
Nazar Antoniuk

Reputation: 11

If anyone still looking for a solution, you can write the XML declaration with the Writer instance using the write_event method:

let mut writer = quick_xml::Writer::new(/* your destination */);
writer.write_event(Event::Decl(BytesDecl::new("1.0", Some("UTF-8"), None)))?;

Then you can continue dealing with the writer or write the rest of your data with the write_serializable method.

Upvotes: 1

Related Questions