RReverser / serde-xml-rs

xml-rs based deserializer for Serde (compatible with 1.0+)
https://crates.io/crates/serde-xml-rs
MIT License
269 stars 90 forks source link

Expose EmitterConfig/Make document declaration optional #193

Open phdavis1027 opened 1 year ago

phdavis1027 commented 1 year ago

I have a use case where I would like to serialize structs in a specific xml-like protocol that does not include any document declarations. I have taken the step of forking this repo to make Serializer::new_from_writer public and wrote this code:

#[derive(Serialize)]
#[serde(rename(serialize = "MsgHeader_PI"))]
pub struct RodsHeader {
    #[serde(rename(serialize = "type"))]
    pub msg_type: String,

    #[serde(rename(serialize = "msgLen"))]
    pub message_length: u32,

    #[serde(rename(serialize = "errorLen"))]
    pub error_length: u32,

    #[serde(rename(serialize = "bsLen"))]
    pub byte_stream_length: u32,

    #[serde(rename(serialize = "intInfo"))]
    pub int_info: u32,
}

fn main() {
    let header = RodsHeader {
        msg_type: "RODS_API_REQ".into(),
        message_length: 0,
        error_length: 0,
        byte_stream_length: 0,
        int_info: 0,
    };

    let mut target: Vec<u8> = Vec::new();
    let writer = EmitterConfig::new()
        .write_document_declaration(false);

    println!("{}", writer.write_document_declaration);
    let writer = writer.create_writer(&mut target);

    let mut serializer = Serializer::new_from_writer(writer);
    header.serialize(&mut serializer).unwrap();
    let header = String::from_utf8(target).unwrap();

    println!("{}", header);
}

Somehow, it still produced this output:

<?xml version="1.0" encoding="UTF-8"?><MsgHeader_PI><type>RODS_API_REQ</type><msgLen>0</msgLen><errorLen>0</errorLen><bsLen>0</bsLen><intInfo>0</intInfo></MsgHeader_PI>

I am a little confused, because as far as I can tell I basically re-implemented to_string, but in any case I'd appreciate guidance or the ability in stable serde-xml-rs to do this.

Thanks in advance for all of y'all's awesome work.