quickxml_to_serde
Convert XML to JSON using quick-xml and serde. Inspired by node2object.
Usage examples
Basic
Dependencies:
use File;
use *;
use xml_string_to_json;
Rust code to perform a conversion:
// read an XML file into a string
let mut xml_file = open?;
let mut xml_contents = String new;
xml_file.read_to_string?;
// convert the XML string into JSON with default config params
let json = xml_string_to_json;
println!;
Custom config
The following config example changes the default behavior to:
- Treat numbers starting with
0
as strings. E.g.0001
will be"0001"
- Do not prefix JSON properties created from attributes
- Use
text
as the JSON property name for values of XML text nodes where the text is mixed with other nodes - Exclude empty elements from the output
let conf = new_with_custom_values;
See embedded docs for Config
struct for more details.
Conversion specifics
- The order of XML elements is not preserved
- Namespace identifiers are dropped. E.g.
<xs:a>123</xs:a>
becomes{ "a":123 }
- Integers and floats are converted into JSON integers and floats. See
Config
members for some fine-tuning. - XML attributes become JSON properties at the same level as child elements. E.g.
1
is converted into
"Test":
- XML prolog is dropped. E.g.
<?xml version="1.0"?>
. - XML namespace definitions are dropped. E.g.
<Tests xmlns="http://www.adatum.com" />
becomes"Tests":{}
- Processing instructions, comments and DTD are ignored
- Presence of CDATA in the XML results in malformed JSON
- XML attributes can be prefixed via
Config::xml_attr_prefix
. E.g. using the default prefix@
converts<a b="y" />
into{ "a": {"@b":"y"} }
. You can use no prefix or set your own value. - Complex XML elements with text nodes put the XML text node value into a JSON property named in
Config::xml_text_node_prop_name
. E.g. settingxml_text_node_prop_name
totext
will convert
1234567
into
- Elements with identical names are collected into arrays. E.g.
7.25
A
3
24.50
B
1
89.99
is converted into
- If
TaxRate
element from the above example was inserted betweenData
elements it would still produce the same JSON with allData
properties grouped into a single array.
Additional info and examples
See mod tests
inside lib.rs for more usage examples.
Edge cases
XML and JSON are not directly compatible for 1:1 conversion without additional hints to the converter. Feel free to post an issue if you come across one.