tafia / quick-xml

Rust high performance xml reader and writer
MIT License
1.23k stars 238 forks source link

Why this very simple code doesn't return the data I expect? #815

Closed frederikhors closed 1 month ago

frederikhors commented 1 month ago

In the simple code below I would like to avoid the <Products> and use directly Vec<Product>:

use quick_xml::de::from_str;
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize, Debug)]
pub struct CustomExport {
    // I need to directly use Vec<Product> instead of another Products struct
    pub Products: Vec<Product>,
}

#[derive(Deserialize, Serialize, Debug)]
pub struct Product {
    pub InternalID: Option<i32>,
    pub Code: Option<String>,
    pub Description: Option<String>,
}

fn main() {
    let xml_data = r#"
    <CustomExport>
        <Products>
            <Product>
                <InternalID>1</InternalID>
                <Code>ABC123</Code>
                <Description>Product 1</Description>
            </Product>
            <Product>
                <InternalID>2</InternalID>
                <Code>DEF456</Code>
                <Description>Product 2</Description>
            </Product>
        </Products>
    </CustomExport>
    "#;

    let result: CustomExport = from_str(xml_data).unwrap();

    println!("{:?}", result);
}

but the result is:

CustomExport { Products: [Product { InternalID: None, Code: None, Description: None }] }

instead of the data I expect.

Why?

Mingun commented 1 month ago

The explanation and way to avoid complicating model are described here