[][src]Crate quickxml_to_serde

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#"<?xml version="1.0" encoding="utf-8"?><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"}}}}

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

NullValue

Defines how empty elements like <x /> should be handled. Ignore -> exclude from JSON, Null -> "x":null, EmptyObject -> "x":{}. EmptyObject is the default option and is how it was handled prior to v.0.4 Using Ignore on an XML document with an empty root element falls back to Null option. E.g. both <a><x/></a> and <a/> are converted into {"a":null}.

Functions

xml_string_to_json

Converts the given XML string into serde::Value using settings from Config struct.