Deserialize same xml tag into collection with serde

Is there a way to deserialize xml tags which are not stored in sequence into a collection using serde and serde-xml-rs?

use serde::Deserialize;

#[derive(Deserialize)]
struct Child1;

#[derive(Deserialize)]
struct Child2;

#[derive(Deserialize)]
struct Parent {
    Child1: Vec<Child1>,
    Child2: Vec<Child2>,
}

fn main() {
    // This can be deserialized
    let works: &'static str = r#"
    <Parent>
        <Child1 />
        <Child1 />
        <Child2 />
    </Parent>
    "#;

    // This cannot be deserialized
    let works_not: &'static str = r#"
    <Parent>
        <Child1 />
        <Child2 />
        <Child1 />
    </Parent>
    "#;

    let _parent: Parent = serde_xml_rs::from_str(works_not).unwrap();
}

When I try to deserialize works_not I get the following error: Error(Custom("duplicate field 'Child1'"), State { next_error: None, backtrace: None })

I'm using

serde = { version = "1.0.99", features = ["derive"] }
serde-xml-rs = "0.3.1"

Check out this issue, it might address your concerns.

I recently tried to do some xml deserialization using using serde, but ended up using a lower level library. Serde-xml-rs works great if the xml fits your serde structure exactly, otherwise it may be difficult to get the result you want.

1 Like