Failed to parse XML with optional element using serde-xml-rs

I have a serde-annotated structs tree and it manages to parse an XML sample, including this snippet:

<bmsg>
    <cmsg>
         <!-- ... -->
    <cmsg>
<bmsg>

Now I am testing a large XML sample file, and the following structures do not work, because sometimes it is <cmsg>..</cmsg>missing. I will deserialize this using:

#[derive(Serialize,Deserialize, Debug)]
struct A {  
    #[serde(rename="bmsg")]
    messages: B,                 // <====
}

#[derive(Serialize,Deserialize, Debug)]
struct B {  // bmsg
    #[serde(rename="cmsg")]
    list: Vec<C>,
}

This led to an error in the second structure:

panicked at 'called `Result::unwrap()` on an `Err` value: missing field `cmsg`

I changed the first structure Vec<>to to deal with an optional element:

#[derive(Serialize,Deserialize, Debug)]
struct A {  
    #[serde(rename="bmsg")]
    messages: Vec<B>,            // <====
}

#[derive(Serialize,Deserialize, Debug)]
struct B {  // bmsg
    #[serde(rename="cmsg")]
    list: Vec<C>,
}

But serde continues to give the same error. I also tried Option<>, but received nothing.

What confuses me the most is what I use Vec<>everywhere and have never encountered this problem.

+4
source share
1

, Option<T> , , .

, -, default, default trait , .

, , :

#[derive(Serialize,Deserialize, Debug)]
struct A {  
    #[serde(rename = "bmsg")]
    messages: B,
}

#[derive(Serialize,Deserialize, Debug)]
struct B {  // bmsg
    #[serde(rename = "cmsg", default)] // <----- use default to call `Default::default()` against this vector
    list: Vec<C>,
}

, . , .

+5

Source: https://habr.com/ru/post/1686960/


All Articles