Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "quickxml_to_serde"
version = "0.6.0"
version = "0.7.0"
authors = ["Alec Troemel <alec@mirusresearch.com>", "Max Voskob <max@onebro.me>"]
description = "Convert between XML JSON using quickxml and serde"
repository = "https://github.com/AlecTroemel/quickxml_to_serde"
Expand Down
19 changes: 19 additions & 0 deletions src/lib.rs
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,25 @@ pub fn xml_string_to_json(xml: String, config: &Config) -> Result<Value, Error>
xml_str_to_json(xml.as_str(), config)
}

/// Returns a Vector of (original xml string, JSON Value) per top level children in the original xml file.
/// This is useful if the XML is a collection of repeated blocks, and you want the original XML of that block.
pub fn map_xml_to_json_per_child(
xml: String,
config: &Config,
) -> Result<Vec<(String, Value)>, Error> {
let root = Element::from_str(xml.as_str())?;
let iterator = root.children().map(|child| {
let mut xml = Vec::new();
child.write_to(&mut xml).expect("successfully write to vec");

let child_xml_str = String::from_utf8(xml).unwrap();
let child_json = xml_to_map(&child, config);
(child_xml_str, child_json)
});

Ok(iterator.collect())
}

/// Returns a tuple for Array and Value enforcements for the current node or
/// `(false, JsonArray::Infer(JsonType::Infer)` if the current path is not found
/// in the list of paths with custom config.
Expand Down
20 changes: 19 additions & 1 deletion src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,8 @@ fn convert_test_files() {
assert!(
file.write_all(to_string_pretty(&json).unwrap().as_bytes())
.is_ok(),
format!("Failed on {:?}", entry.as_os_str())
"Failed on {:?}",
entry.as_os_str()
);
}
}
Expand Down Expand Up @@ -463,3 +464,20 @@ fn test_regex_json_type_overrides() {
let result = xml_string_to_json(String::from(xml), &config);
assert_eq!(expected, result.unwrap());
}

#[test]
fn test_map_xml_to_json_per_child() {
let xml = r#"
<root>
<a><b>123</b></a>
<a><b>456</b></a>
</root>
"#;

let expected = vec![
(String::from("<a><b>123</b></a>"), json!({"a": { "b": 123}})),
(String::from("<a><b>456</b></a>"), json!({"a": { "b": 456}})),
];
let result = map_xml_to_json_per_child(String::from(xml), &Config::new_with_defaults());
assert_eq!(expected, result.unwrap());
}
Loading