1 unstable release
new 0.12.0 |
|
---|---|
0.0.1 | Jan 17, 2025 |
#350 in #xml
109 downloads per month
Used in einvoice
24KB
529 lines
This is a personal fork of https://crates.io/crates/yaserde and https://crates.io/crates/yaserde_derive , which are licensed under the MIT license. Please ignore.
lib.rs
:
YaSerDe
YaSerDe is a framework for serializing and deserializing Rust data structures efficiently and generically from and into XML.
YaSerDe makes it easy to serialize XML documents given an properly annotated struct.
Please refer to the examples
directory for the complete code shown below.
Serialize
For instance, let's say that one wants to generate a XML file for the Rust-Embedded community. A well known XML file for microcontrollers is called SVD and it can be defined on YaSerDe via structs like so:
use einvoice_deps_yaserde_derive::YaSerialize;
#[derive(PartialEq, Debug, YaSerialize)]
#[yaserde(rename = "device")]
struct Device {
#[yaserde(attribute = true)]
schemaversion: String,
#[yaserde(attribute = true)]
xmlns: String,
#[yaserde(attribute = true)]
xsnonamespaceschemalocation: String,
attributes: DeviceAttributes
}
#[derive(PartialEq, Debug, YaSerialize)]
struct DeviceAttributes {
vendor: String,
}
The interspersed #[yaserde()]
macros give some indication of what the resulting XML
Will look like, namely, a short snippet of the struct above in XML would be depending on
concrete values passed to the struct (not shown):
(...)
<device schemaversion: "1.0-example", xmlns: "ns:.... example"
xsnonamespaceschemalocation: "foo_bar_baz">
<devattributes>
</devattributes>
(...)
Notice the important difference in XML output representation between attributes
vs
child
, since SVD expects information in that particular arrangement. YaSerDe allows that
serialized XML to be valid unlike other Rust XML (de)serialization crates (i.e quick-xml).
Also the last DevAttrs
struct field is indeed another struct, so one can chain several
structs to compose the XML structure (again, see examples folder for the complete
example).
[dependencies]
# serde = { version = "1.0.123", features = [ "derive" ] }
# quick-xml = { version = "0.21.0", features = [ "serialize" ] }
yaserde = "0.5.1"
yaserde_derive = "0.5.1"
Last but not least, in order to have a nice, pretty printed XML output one can do:
// Display pretty printed XML
let yaserde_cfg = yaserde::ser::Config{
perform_indent: true,
.. Default::default()
};
println!("{}", yaserde::ser::to_string_with_config(&dev, &yaserde_cfg).ok().unwrap());
Avoid using either {:?}
or {:#?}
println! formatters since it'll garble the output of your
XML.
Dependencies
~290–490KB