Crate quickxml_to_serde[−][src]
Expand description
quickxml_to_serde
Fast and flexible conversion from XML to JSON using quick-xml and serde. Inspired by node2object.
This crate converts XML elements, attributes and text nodes directly into corresponding JSON structures. Some common usage scenarios would be converting XML into JSON for loading into No-SQL databases or sending it to the front end application.
Because of the richness and flexibility of XML some conversion behavior is configurable:
- attribute name prefixes
- naming of text nodes
- number format conversion
Usage example
extern crate quickxml_to_serde; use quickxml_to_serde::{xml_string_to_json, Config, NullValue}; fn main() { let xml = r#"<a attr1="1"><b><c attr2="001">some text</c></b></a>"#; let conf = Config::new_with_defaults(); let json = xml_string_to_json(xml.to_owned(), &conf); println!("{}", json.expect("Malformed XML").to_string()); let conf = Config::new_with_custom_values(true, "", "txt", NullValue::Null); let json = xml_string_to_json(xml.to_owned(), &conf); println!("{}", json.expect("Malformed XML").to_string()); }
- Output with the default config:
{"a":{"@attr1":1,"b":{"c":{"#text":"some text","@attr2":1}}}}
- Output with a custom config:
{"a":{"attr1":1,"b":{"c":{"attr2":"001","txt":"some text"}}}}
Additional features
Use quickxml_to_serde = { version = "0.4", features = ["json_types"] }
to enable support for enforcing JSON types
for some XML nodes using xPath-like notations. Example for enforcing attribute attr2
from the snippet above
as JSON String regardless of its contents:
use quickxml_to_serde::{Config, JsonArray, JsonType}; #[cfg(feature = "json_types")] let conf = Config::new_with_defaults() .add_json_type_override("/a/b/c/@attr2", JsonArray::Infer(JsonType::AlwaysString));
Detailed documentation
See README in the source repo for more examples, limitations and detailed behavior description.
Testing your XML files
If you want to see how your XML files are converted into JSON, place them into ./test_xml_files
directory
and run cargo test
. They will be converted into JSON and saved in the saved directory.
Structs
Config | Tells the converter how to perform certain conversions. See docs for individual fields for more info. |
Enums
JsonArray | Defines how the values of this Node should be converted into a JSON array with the underlying types. |
JsonType | Defines which data type to apply in JSON format for consistency of output.
E.g., the range of XML values for the same node type may be |
NullValue | Defines how empty elements like |
Functions
xml_string_to_json | Converts the given XML string into |