4

我有以下结构:

struct Artist {
    name: String,
    image: String,
}

struct Album {
    title: String,
    artists: Vec<Artist>,
}

我需要生成如下所示的 XML:

<album>
  <title>Some title</title>
  <artist>
    <name>Bonnie</name>
    <image>http://example.com/bonnie.jpg</image>
  </artist>
  <artist>
    <name>Cher</name>
    <image>http://example.com/cher.jpg</image>
  </artist>
</album>

如何使用 serde 序列化/反序列化为上述 XML 格式,特别是关于扁平化artists向量以生成多个artist元素?这是我无法更改的第三方格式:-(

4

1 回答 1

3

crate 是已弃用的crateserde-xml-rs的替代品,serde_xml并支持将数据结构序列化为您想要的表示形式的 XML。

extern crate serde;
extern crate serde_xml_rs;

use serde::ser::{Serialize, Serializer, SerializeMap, SerializeStruct};

struct Artist {
    name: String,
    image: String,
}

impl Serialize for Artist {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer
    {
        let mut map = serializer.serialize_map(Some(2))?;
        map.serialize_entry("name", &self.name)?;
        map.serialize_entry("image", &self.image)?;
        map.end()
    }
}

struct Album {
    title: String,
    artists: Vec<Artist>,
}

impl Serialize for Album {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer
    {
        let len = 1 + self.artists.len();
        let mut map = serializer.serialize_struct("album", len)?;
        map.serialize_field("title", &self.title)?;
        for artist in &self.artists {
            map.serialize_field("artist", artist)?;
        }
        map.end()
    }
}

fn main() {
    let album = Album {
        title: "Some title".to_owned(),
        artists: vec![
            Artist {
                name: "Bonnie".to_owned(),
                image: "http://example.com/bonnie.jpg".to_owned(),
            },
            Artist {
                name: "Cher".to_owned(),
                image: "http://example.com/cher.jpg".to_owned(),
            },
        ],
    };

    let mut buffer = Vec::new();
    serde_xml_rs::serialize(&album, &mut buffer).unwrap();
    let serialized = String::from_utf8(buffer).unwrap();
    println!("{}", serialized);
}

输出是:

<album>
  <title>Some title</title>
  <artist>
    <name>Bonnie</name>
    <image>http://example.com/bonnie.jpg</image>
  </artist>
  <artist>
    <name>Cher</name>
    <image>http://example.com/cher.jpg</image>
  </artist>
</album>
于 2018-02-25T18:37:38.800 回答