Rust Serde:直接将XML反序列化为Vec <T>

时间:2019-10-26 14:54:00

标签: xml serialization rust deserialization serde

我需要使用serde来序列化一些XML数据。 数据具有一种模式,其中多个标记名称(例如CATS,DOGS)将包含多个单个标记(CAT,DOG)的子标记实例,如下所示:

<pets>
  <cats>
    <cat>
      <name>
          cat 1
      </name>
    </cat>
    <cat>
      <name>
          cat 2
      </name>
    </cat>
  </cats>
  <dogs>
    <dog>
      <name>
          dog 1
      </name>
    </dog>
    <dog>
      <name>
          dog 2
      </name>
    </dog>
  </dogs>
</pets>

现在,我可以使用serdeserde-xml-rs进行反序列化了:

use serde::{Serialize, Deserialize};
use serde_xml_rs;

#[derive(Debug, Serialize, Deserialize)]
struct Pets {
    pub cats: Cats,
    pub dogs: Dogs,
}

#[derive(Debug, Serialize, Deserialize)]
struct Cats {
    pub cat: Vec<Cat>,
}

#[derive(Debug, Serialize, Deserialize)]
struct Dogs {
    pub dog: Vec<Dog>,
}

#[derive(Debug, Serialize, Deserialize)]
struct Cat {
    name: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct Dog {
    name: String,
}


fn main() {
    let s = xml_string_from_above;
    let pets: Pets = serde_xml_rs::from_str(s).unwrap();
    println!("{:#?}", pets);
}

问题:我是否可以使用Serde hack删除中间结构CatsDogs并简单地在向量中获取多个实例?

#[derive(Debug, Serialize, Deserialize)]
struct SlimmedPets {
    pub cats: Vec<Cat>,
    pub dogs: Vec<Dog>,
}

在序列化SlimmedPets结构时仍返回相同的XML?

0 个答案:

没有答案