Convert XML to JSON using quick-xml and serde. Inspired by node2object.
Dependencies:
rust
use std::fs::File;
use std::io::prelude::*;
use quickxml_to_serde::xml_string_to_json;
Rust code to perform a conversion:
```rust
// read an XML file into a string
let mut xmlfile = File::open("test.xml")?;
let mut xmlcontents = String::new();
xmlfile.readtostring(&mut xmlcontents)?;
// convert the XML string into JSON with default config params let json = xmlstringtojson(xmlcontents, &Config::newwithdefaults());
println!("{}", json); ```
The following config example changes the default behavior to:
0
as strings. E.g. 0001
will be "0001"
text
as the JSON property name for values of XML text nodes where the text is mixed with other nodesrust
let conf = Config::new_with_custom_values(true, "", "text", NullValue::Ignore);
See embedded docs for Config
struct for more details.
<xs:a>123</xs:a>
becomes { "a":123 }
Config
members for some fine-tuning.xml
<Test TestId="0001">
<Input>1</Input>
</Test>
is converted into
json
"Test":
{
"Input": 1,
"TestId": "0001"
}
<?xml version="1.0"?>
.<Tests xmlns="http://www.adatum.com" />
becomes "Tests":{}
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. Config::xml_text_node_prop_name
. E.g. setting xml_text_node_prop_name
to text
will convert
xml
<CardNumber Month="3" Year="19">1234567</CardNumber>
into
json
{
"CardNumber": {
"Month": 3,
"Year": 19,
"text": 1234567
}
}
xml
<Root>
<TaxRate>7.25</TaxRate>
<Data>
<Category>A</Category>
<Quantity>3</Quantity>
<Price>24.50</Price>
</Data>
<Data>
<Category>B</Category>
<Quantity>1</Quantity>
<Price>89.99</Price>
</Data>
</Root>
is converted into
json
{
"Root": {
"Data": [
{
"Category": "A",
"Price": 24.5,
"Quantity": 3
},
{
"Category": "B",
"Price": 89.99,
"Quantity": 1
}
],
"TaxRate": 7.25
}
}
TaxRate
element from the above example was inserted between Data
elements it would still produce the same JSON with all Data
properties grouped into a single array.See mod tests
inside lib.rs for more usage examples.
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.