Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get the error "missing field" when deserializing XML with serde-xml-rs, even though the element is present?

Tags:

xml

rust

serde

I have the following XML file

<?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>

I want to deserialize it using serde-xml-rs into this struct hierarchy:

#[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,
}

I am trying to read from the file using the below code.

let file = File::open("data/sample_1.xml").unwrap();
let project: Project = from_reader(file).unwrap();

I get this error saying "missing field 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.
like image 300
joydeep bhattacharjee Avatar asked Sep 01 '25 04:09

joydeep bhattacharjee


1 Answers

Following the example at the GitHub repository, you are missing an annotation:

#[derive(Deserialize, Debug)]
struct Libraries {
    #[serde(rename = "library")]
    libraries: Vec<Library>
}

With that I get the correct deserialized representation of your XML file

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"
            }
        ]
    }
}
like image 55
hellow Avatar answered Sep 02 '25 17:09

hellow