RReverser / serde-xml-rs

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

Adjacently tagged enums deserialization doesn't work #179

Closed xvenge00 closed 2 years ago

xvenge00 commented 2 years ago

Hi, I'm having trouble deserializing following XML

<struct>
  <member>
      <name>created</name>
      <value>
          Johny
      </value>
  </member>
  <member>
      <name>description</name>
      <value>
          Something was created
      </value>
  </member>
</struct>

I would expect using adjacently tagged enums would work, but I get error. called `Result::unwrap()` on an `Err` value: Custom { field: "invalid type: map, expected variant identifier" } thread 'entities::tests::test_serialize_member' panicked at 'called `Result::unwrap()` on an `Err` value: Custom { field: "invalid type: map, expected variant identifier" }'

Serialization looks OK <member><name>created</name><value>Johny</value></member>, only problem is with deserialization.

Minimal example to reproduce looks as

#[cfg(test)]
mod tests {
    use serde_json;
    use serde_xml_rs;
    use serde::{Deserialize, Serialize};

    #[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
    #[serde(tag = "name", content = "value")]
    #[serde(rename = "member")]
    #[serde(rename_all = "snake_case")]
    enum Member {
        Created(String),
        Description(String),
    }

    #[test]
    fn test_serialize_member() {
        let m = Member::Created("Johny".to_owned());

        let m_serialized: String = serde_xml_rs::to_string(&m).unwrap();
        println!("{}", m_serialized);

        let m2: Member = serde_xml_rs::from_str(m_serialized.as_str()).unwrap();
        println!("{:?}", m2);
        assert_eq!(m, m2);
    }
}

with Cargo.toml

[package]
name = "foo"
version = "0.1.0"
edition = "2021"

[dependencies]
serde-xml-rs = { version = "0.5.1" }
serde = { version = "1.0", features = ["derive"] }

Equivalent code with serde_json works fine. {"name":"created","value":"Johny"}

punkstarman commented 2 years ago

This is fixed now in the latest version (0.6.0).

The minimal example you provided will still fail, but only because the serializer will tack on the XML prolog (<?xml version="1.0" encoding="UTF-8"?>).