rust - 使用 serde 时如何将向量 'flatten' 生成多个 XML 元素?

标签 rust serde

我有以下结构:

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 元素?这是我无法更改的第三方格式:-(

最佳答案

serde-xml-rs crate 是已弃用的 serde_xml crate 的替代品,它支持将数据结构序列化为您想要的表示形式的 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>

关于rust - 使用 serde 时如何将向量 'flatten' 生成多个 XML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41416913/

相关文章:

rust - Rust 的 glob 函数代表什么时间点?

websocket - 我想在 HashMap 中保留一个引用,但我无法正确指定生命周期

graph - 如何使用Serde和Petgraph对图进行序列化和反序列化?

Rust:如何限制派生特征的类型参数

rust - 如何在不派生结构的情况下使用 serde_json 获取 JSON 文件中的一个特定项目?

rust - 最终用户实用程序/应用程序应该在 crates.io 上注册吗?

rust - 如何使用 wasm-bindgen 调用作为模块的 JavaScript 函数?

rust - rust “Types differ in mutability”

rust - 如何使用Serde反序列化Prost枚举?

xml - 无法使用 serde-xml-rs 解析带有可选元素的 XML