我正在使用serde-xml-rs进行简单的信息传输,我或其他任何人以后都可以更改而无需在Rust中进行编码。
它看起来像这样:
<?xml version="1.0" encoding="UTF-8" ?>
<root>
<mass>1</mass>
<pole_radius>1</pole_radius>
<eq_radius>1</eq_radius>
<atmos_n2>1</atmos_n2>
<atmos_o2>1</atmos_o2>
<atmos_ar>1</atmos_ar>
<atmos_co2>1</atmos_co2>
<atmos_ne>1</atmos_ne>
<atmos_he>1</atmos_he>
<atmos_ch4>1</atmos_ch4>
<atmos_h20>1</atmos_h20>
</root>
哪个有效,但是有点丑陋,需要很多东西。我希望它更像这样:
<?xml version="1.0" encoding="UTF-8" ?>
<root>
<planetary>
<mass>1</mass>
<pole_radius>1</pole_radius>
<eq_radius>1</eq_radius>
</planetary>
<atmos>
<n2>1</n2>
<o2>1</o2>
<!-- slimmed it down so that it saves space for this post -->
<atmos>
</root>
我不确定如何使用serde_xml_rs
与该系统一起使用。这是目前的设置方式,在读取第一个XML代码段时有效:
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_xml_rs;
use std::fs::File;
use std::io::Read;
#[derive(Serialize, Deserialize)]
struct LevelData {
mass: f64,
// more here, again slimmed for the post
}
fn init() {
let mut file = File::open("Level.xml").unwrap();
let mut buff = String::new();
file.read_to_string(&mut buff).unwrap();
let level_data: LevelData = serde_xml_rs::from_str(&buff).unwrap();
}
fn main() {
init();
}
答案 0 :(得分:3)
通常,您可以通过在Rust类型中镜像相同的数据结构来做到这一点:
#[derive(Serialize, Deserialize)]
struct LevelData {
planetary: PlanetaryData,
}
#[derive(Serialize, Deserialize)]
struct PlanetaryData {
mass: f64,
}