1

I have to deserialize an XML file into Rust structs:

<root date="2020">
  <buecher>
    <buch id="123">
      <iban>123</iban>
    </buch>
    <buch id="456">
      <iban>456</iban>
    </buch>
  </buecher>
</root>
extern crate serde;
extern crate serde_xml_rs;

#[macro_use]
extern crate serde_derive;

use std::fs::File;
use std::io::BufReader;

#[derive(Deserialize, Debug)]
struct Root {
    date: String,
    buecher: Buecher,
}

#[derive(Deserialize, Debug)]
struct Buecher {
    buch: Vec<Buch>,
}

#[derive(Deserialize, Debug)]
struct Buch {
    id: String,
    iban: String,
}

fn main() {
    let file = File::open("data/test.xml");
    if file.is_ok() {
        let buf_reader = BufReader::new(file.unwrap());
        let data: Root = serde_xml_rs::from_reader(buf_reader).unwrap();
        println!("{:#?}", data);
    }
}

Is it possible to map the buch children directly without the intermediate buecher struct somehow?

Something like

#[derive(Deserialize, Debug)]
struct Root {
    date: String,
    #[serde(rename = "buecher/buch")]
    buecher: Vec<Buch>,
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Pascal
  • 2,059
  • 3
  • 31
  • 52
  • Your question might be answered by the answers of [How to flatten a `Vec` field when serializing a struct with serde?](https://stackoverflow.com/q/62363984/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Sep 08 '20 at 14:04
  • no it doesn't. I have to deserialize and want to remap one level. Don't know how to explain further. My attempt to rename with a `a/b` mapping doesn't work and the flattening option applies to another situation – Pascal Sep 08 '20 at 14:18
  • "Unfortunately you can't" doesn't answer your question? – Shepmaster Sep 08 '20 at 14:23
  • See also [How to transform fields during deserialization using Serde?](https://stackoverflow.com/q/46753955/155423). – Shepmaster Sep 08 '20 at 14:24
  • Simplest solution would be to live with the `buecher` level in between. But i will try your suggestion using a custom deserialize function now – Pascal Sep 08 '20 at 14:42

0 Answers0