gpt4 book ai didi

xml - 为什么在使用 serde-xml-rs 反序列化 XML 时出现错误 "missing field",即使该元素存在?

转载 作者:行者123 更新时间:2023-11-29 08:05:51 30 4
gpt4 key购买 nike

我有以下 XML 文件

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<project name="project-name">
<libraries>
<library groupId="org.example" artifactId="&lt;name&gt;" version="0.1"/>
<library groupId="com.example" artifactId="&quot;cool-lib&amp;" 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();

我收到此错误消息“缺少字段”:

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.

最佳答案

按照 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"
}
]
}
}

关于xml - 为什么在使用 serde-xml-rs 反序列化 XML 时出现错误 "missing field",即使该元素存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55707588/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com