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

时间:2019-04-16 11:55:53

标签: xml rust serde

我有以下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.

1 个答案:

答案 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"
            }
        ]
    }
}