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

Serializing $value enum variant doesn't work

Open tyilo opened this issue 3 years ago • 1 comments

Cargo.toml:

[package]
name = "quick-xml-test"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
serde = { version = "1.0.139", features = ["derive"] }
quick-xml = { version = "0.23.0", features = ["serialize" ] }

src/main.rs:

use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
enum State {
    A,
    B,
    C,
}

#[derive(Debug, Deserialize, Serialize)]
struct StateOuter {
    #[serde(rename = "$value")]
    state: State,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Root {
    state: StateOuter,
}

impl Root {
    pub fn new() -> Self {
        Self { state: StateOuter { state: State::B } }
    }
}

fn main() {
    let xml = "<root><state>B</state></root>";
    println!("Deserialized: {:?}", quick_xml::de::from_str::<Root>(&xml));

    let root = Root::new();
    println!("Serialized: {:?}", quick_xml::se::to_string(&root));
}

Output:

Deserialized: Ok(Root { state: StateOuter { state: B } })
Serialized: Ok("<Root><state><B/></state></Root>")

Expected output:

Deserialized: Ok(Root { state: StateOuter { state: B } })
Serialized: Ok("<Root><state>B</state></Root>")

As you can see deserialization works, but serialization does not.

tyilo avatar Jul 19 '22 09:07 tyilo

Efforts have not yet been put into the correct representation of enum, so many obvious (in fact, not all are obvious) things do not work. First of all, it's need to write consistent, composable rules to represent various serde enum representations. I've started this work in my doc branch, but have not yet time to finish it. You can help by working through this aspect of, if you wish.

Mingun avatar Jul 19 '22 15:07 Mingun