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>