为什么在使用serde-xml-rs反序列化XML时会出现错误“缺少字段”,即使该元素存在?

问题描述 投票:2回答:1

我有以下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();

我得到这个错误说“缺少字段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.
xml rust serde
1个回答
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"
            }
        ]
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.