[记]在rust中使用xml,xml的序列化与反序列化
序
在rust中有好几个xml库,但我个人比较推荐的是quick_xml库,这个库的序列化和反序列化使用体验比较好。
启用quick_xml的feature
quick-xml = { version = "0.31.0",features=["serde","serialize"] }
serde = {version="1.0",features=["derive"]}
qucik_mxl的宏体验
依靠强大的宏,quick_xml使用结构体和枚举即可实现xml结构的一一对应。
标签内属性使用宏进行标记
->https://docs.rs/quick-xml/latest/quick_xml/de/
pub struct CalibrationData{
#[serde(rename = "@xmlns:xsi")]
xmlns:String,
CalConfig:Vec<CalConfig>,
}
<CalibrationData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
...
</CalibrationData>
#[derive(Deserialize)]
struct AnyName {
#[serde(rename = "@one")]
one: T,
#[serde(rename = "@two")]
two: U,
}
<any-tag one="..." two="..."/>
#[derive(Deserialize)]
struct AnyName {
one: T,
two: U,
}
<any-tag>
<one>...</one>
<two>...</two>
</any-tag>
#[derive(Deserialize)]
struct AnyName {
#[serde(rename = "@field")]
attribute: T,
field: U,
}
<any-tag field="...">
<field>...</field>
</any-tag>
#[derive(Deserialize)]
struct AnyName {
#[serde(rename = "@optional")]
optional: Option<T>,
}
<any-tag optional="..."/><!-- Some("...") -->
<any-tag optional=""/> <!-- Some("") -->
<any-tag/> <!-- None -->
#[derive(Deserialize)]
struct AnyName {
#[serde(default)]
item: Vec<Item>,
}
<any-tag>
<item/>
<item/>
<item/>
</any-tag>
序列化反序列化
use serde::Serialize;
use quick_xml::writer::Writer;
use quick_xml::se::Serializer;
use quick_xml::de::from_str;
use quick_xml::reader::Reader;
if let Ok(sd) = quick_xml::se::to_string(&sedd){
println!("sd{}",sd);
}
let okxml =std::fs::read_to_string("CalDB_NET.xml")?;
let sedd = from_str::<CalibrationData>(&okxml).unwrap();
-------------====================分割线====================-------------