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 = Stringnew;
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
0as strings. E.g.0001will be"0001" - Do not prefix JSON properties created from attributes
- Use
textas 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;
Enforcing JSON types
Matching based on absolute path or regex
You can override the type of absolute paths within the XML
let config = new_with_defaults
.add_json_type_override;
Or you can match based on a regex!
let config = new_with_defaults
.add_json_type_override;
Strings
The default for this library is to attempt to infer scalar data types, which can be int, float, bool or string in JSON. Sometimes it is not desirable like in the example below. Let's assume that attribute id is always numeric and can be safely converted to JSON integer.
The card_number element looks like a number for the first two users and is a string for the third one. This inconsistency in JSON typing makes it
difficult to deserialize the structure, so we may be better off telling the converter to use a particular JSON data type for some XML nodes.
Andrew
000156
John
100263
Mary
100263a
Use quickxml_to_serde = { version = "0.4", features = ["json_types"] } feature in your Cargo.toml file to enable support for enforcing JSON types for some XML nodes using xPath-like notations.
Sample XML document:
true
Configuration to make attribute attr1="007" always come out as a JSON string:
let conf = new_with_defaults.add_json_type_override;
Configuration to make both attributes and the text node of <b /> always come out as a JSON string:
let conf = new_with_defaults
.add_json_type_override
.add_json_type_override
.add_json_type_override;
Boolean
The only two valid boolean values in JSON are true and false. On the other hand, values such as True, False,1 and 0 are common in programming languages and data formats. Use JsonType::Bool(...) type with the list of "true" values to convert arbitrary boolean values into JSON bool.
let conf = new_with_defaults
.add_json_type_override;
Arrays
Multiple nodes with the same name are automatically converted into a JSON array. For example,
1
2
is converted into
By default, a single element like
1
is converted into a scalar value or a map
You can use add_json_type_override() with JsonArray::Always() to create a JSON array regardless of the number of elements so that <a><b>1</b></a> becomes { "a": { "b": [1] } }.
JsonArray::Always() and JsonArray::Infer() can specify what underlying JSON type should be used, e.g.
JsonArray::Infer(JsonType::AlwaysString)- infer array, convert the values to JSON stringJsonArray::Always(JsonType::Infer)- always wrap the values in a JSON array, infer the value typesJsonArray::Always(JsonType::AlwaysString)- always wrap the values in a JSON array and convert values to JSON string
let config = new_with_defaults
.add_json_type_override;
Conversion of empty XML nodes like <a><b /></a> depends on NullValue setting. For example,
let config = new_with_custom_values
.add_json_type_override;
converts <a><b /></a> to
and the same config with NullValue::Null converts it to
It is not possible to get an empty array like {"a": { "b": [] }}.
See embedded docs for Config struct and its members 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, unless the JSON type is specified in
Config. - 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_nametotextwill 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
TaxRateelement from the above example was inserted betweenDataelements it would still produce the same JSON with allDataproperties grouped into a single array.
Additional info and examples
See tests.rs for more usage examples.
Edge cases
XML and JSON are not directly compatible for 1:1 conversion without additional hints to the converter. Please, post an issue if you come across any incorrect conversion.