How to deserialize xml file into rust serde structure
For example, I have a xml file like this:
<?xml version="1.0"?>
<Foo>
<title>Example</title>
<description>An example description</description>
<bar>
<title>First</title>
<description>First description</description>
</bar>
<bar>
<title>Second</title>
<description>Second description</description>
</bar>
</Foo>
There is a rust library that work with xml file quickly, called quick_xml, then use it with serde lib to deserialize it to rust structure.
First, create rust struct with derive serde
use serde::Deserialize;
#[derive(Debug, Default, Deserialize)]
#[serde(default, rename_all = "camelCase")]
struct Xml {
foo: Foo,
}
#[derive(Debug, Default, Deserialize)]
#[serde(default, rename_all = "camelCase")]
struct Foo {
title: String,
description: String,
bar: Vec<Bar>,
}
#[derive(Debug, Deserialize)]
#[serde(default, rename_all = "camelCase")]
struct Bar {
title: String,
description: String,
}
Use quick_xml to read from the file to struct
use anyhow::Context;
use quick_xml::de::from_str;
let xml: Xml = from_str(xml.as_str()).context("Parse into the RSS")?;
println!("{xml:#?}");
[!NOTE] I found an error if there are the duplicate fields at the root level which will panic the thread, but it's oay for the child level to be duplicate, i.e. the 'Bar' level. Haven't found the solution for that.