gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:01:00 25 4
gpt4 key购买 nike

我有以下结构:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com