use quick_xml::events::Event;
use quick_xml::Reader;
use serde_json::{Map, Value};
pub(super) fn parse_xml_string(xml_str: &str) -> Result<Value, String> {
let mut reader = Reader::from_str(xml_str);
reader.trim_text(true);
let mut buf = Vec::new();
loop {
match reader.read_event_into(&mut buf) {
Ok(Event::Start(ref e)) => {
let tag = String::from_utf8_lossy(e.name().as_ref()).into_owned();
let val = parse_xml_element(&mut reader, &tag)?;
return Ok(Value::Object(Map::from_iter([(tag, val)])));
}
Ok(Event::Empty(ref e)) => {
let tag = String::from_utf8_lossy(e.name().as_ref()).into_owned();
return Ok(Value::Object(Map::from_iter([(tag, Value::Object(Map::new()))])));
}
Ok(Event::Eof) => return Err("Empty XML document".to_string()),
Err(e) => return Err(format!("XML error: {}", e)),
_ => {}
}
buf.clear();
}
}
fn parse_xml_element(reader: &mut Reader<&[u8]>, current_tag: &str) -> Result<Value, String> {
let mut buf = Vec::new();
let mut children: Vec<(String, Value)> = Vec::new();
let mut text_content = String::new();
loop {
match reader.read_event_into(&mut buf) {
Ok(Event::Start(ref e)) => {
let tag = String::from_utf8_lossy(e.name().as_ref()).into_owned();
let val = parse_xml_element(reader, &tag)?;
children.push((tag, val));
}
Ok(Event::Empty(ref e)) => {
let tag = String::from_utf8_lossy(e.name().as_ref()).into_owned();
children.push((tag, Value::String(String::new())));
}
Ok(Event::Text(ref e)) => {
text_content.push_str(&e.unescape().map_err(|err| err.to_string())?);
}
Ok(Event::End(ref e)) if e.name().as_ref() == current_tag.as_bytes() => break,
Ok(Event::Eof) => return Err(format!("Unexpected EOF inside tag: {}", current_tag)),
Err(e) => return Err(format!("XML error: {}", e)),
_ => {}
}
buf.clear();
}
if children.is_empty() {
return Ok(coerce_xml_scalar(text_content.trim()));
}
let first_tag = &children[0].0;
let collapse = (children.len() > 1 && children.iter().all(|(t, _)| t == first_tag))
|| (children.len() == 1 && matches!(first_tag.as_str(), "item" | "step"));
if collapse {
return Ok(Value::Array(children.into_iter().map(|(_, v)| v).collect()));
}
let mut map = Map::new();
for (tag, val) in children {
match map.get_mut(&tag) {
Some(Value::Array(arr)) => arr.push(val),
Some(prev) => *prev = Value::Array(vec![prev.clone(), val]),
None => {
map.insert(tag, val);
}
}
}
Ok(Value::Object(map))
}
fn coerce_xml_scalar(text: &str) -> Value {
if text.eq_ignore_ascii_case("true") {
Value::Bool(true)
} else if text.eq_ignore_ascii_case("false") {
Value::Bool(false)
} else if let Ok(i) = text.parse::<i64>() {
Value::Number(i.into())
} else if let Some(num) = text.parse::<f64>().ok().and_then(serde_json::Number::from_f64) {
Value::Number(num)
} else {
Value::String(text.to_string())
}
}