我有以下XML文件
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<project name="project-name">
<libraries>
<library groupId="org.example" artifactId="<name>" version="0.1"/>
<library groupId="com.example" artifactId=""cool-lib&" version="999"/>
</libraries>
</project>
我想使用serde-xml-rs将其反序列化到此结构层次结构中:
#[derive(Deserialize, Debug)]
struct Project {
name: String,
libraries: Libraries
}
#[derive(Deserialize, Debug)]
struct Libraries {
libraries: Vec<Library>,
}
#[derive(Deserialize, Debug)]
struct Library {
groupId: String,
artifactId: String,
version: String,
}
我正在尝试使用以下代码从文件中读取数据。
let file = File::open("data/sample_1.xml").unwrap();
let project: Project = from_reader(file).unwrap();
我收到此错误,提示“缺少字段libraries
”:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error(Custom("missing field `libraries`"), State { next_error: None, backtrace: None })', src/libcore/result.rs:997:5
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
答案 0 :(得分:3)
按照GitHub repository的示例,您缺少注释:
#[derive(Deserialize, Debug)]
struct Libraries {
#[serde(rename = "library")]
libraries: Vec<Library>
}
这样我就可以正确地反序列化XML文件了
project = Project {
name: "project-name",
libraries: Libraries {
libraries: [
Library {
groupId: "org.example",
artifactId: "<name>",
version: "0.1"
},
Library {
groupId: "com.example",
artifactId: "\"cool-lib&",
version: "999"
}
]
}
}