3

I want to deserialize a number (for example, u32) from an XML attribute.

#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_xml_rs as serde_xml;


#[derive(Deserialize, Debug)]
#[serde(rename = "objects")]
pub struct Objects {
    pub foo: u32
}

fn main() {
    let result_string = r#"<?xml version="1.0" encoding="UTF-8"?>
    <objects foo="42"></objects>"#;
    let deserialized: Objects= serde_xml::deserialize(result_string.as_bytes()).expect("Parse error!");
}

But after execution, I get the following error

thread 'main' panicked at 'Parse error!: invalid type: string "42", expected u32'

I know about #[serde(deserialize_with="...")] annotation, but is there an easier way, (for example use serde_xml_rs crate)?

dtolnay
  • 9,621
  • 5
  • 41
  • 62
chabapok
  • 921
  • 1
  • 8
  • 14
  • 1
    Without the attribute, you would need to express the types in some sort of schema. But unfortunately `serde_xml_rs` does not support schema or DTD. – Peter Hall Jun 28 '18 at 12:54
  • Maybe `Option` would work to handle non-numeric cases – user25064 Jun 28 '18 at 13:01
  • https://stackoverflow.com/questions/27043268/convert-a-string-to-int-in-rust Why not just append the str::parse:: to your deserialize function? – stevensonmt Jun 28 '18 at 18:16

1 Answers1

0

Do not use 0.2.1. Add to Cargo.toml:

serde-xml-rs = { git= "https://github.com/RReverser/serde-xml-rs.git"}

Using serde-xml-rs from master fixes this issue.

chabapok
  • 921
  • 1
  • 8
  • 14