Skip to main content

uddf_sdk/utils/
xml.rs

1use quick_xml::se::to_string_with_root;
2use serde::Serialize;
3
4pub trait ToXml {
5    /// Convert the struct to an XML string.
6    fn to_xml(&self) -> String;
7}
8
9impl<T> ToXml for T
10where
11    T: Serialize,
12{
13    /// Convert the struct to an XML string.
14    fn to_xml(&self) -> String {
15        let type_name = std::any::type_name::<Self>();
16        let struct_name = type_name.split("::").last().unwrap().to_lowercase();
17        to_string_with_root(&struct_name, &self).unwrap()
18    }
19}
20
21#[cfg(test)]
22mod tests {
23    use super::*;
24    use serde::Serialize;
25
26    #[derive(Serialize)]
27    struct TestStruct {
28        field1: String,
29        field2: i32,
30    }
31
32    #[test]
33    fn test_to_xml_basic() {
34        let test_struct = TestStruct {
35            field1: "value1".to_string(),
36            field2: 42,
37        };
38        let xml = test_struct.to_xml();
39        let expected_xml = "<teststruct><field1>value1</field1><field2>42</field2></teststruct>";
40        assert_eq!(xml, expected_xml);
41    }
42
43    #[test]
44    fn test_to_xml_empty_struct() {
45        #[derive(Serialize)]
46        struct EmptyStruct;
47
48        let empty_struct = EmptyStruct;
49        let xml = empty_struct.to_xml();
50        println!("{}", xml);
51        assert_eq!(xml, "<emptystruct/>");
52    }
53
54    #[test]
55    fn test_to_xml_nested_struct() {
56        #[derive(Serialize)]
57        struct NestedStruct {
58            inner: TestStruct,
59        }
60
61        let nested_struct = NestedStruct {
62            inner: TestStruct {
63                field1: "inner_value".to_string(),
64                field2: 100,
65            },
66        };
67        let xml = nested_struct.to_xml();
68        assert_eq!(
69            xml,
70            "<nestedstruct><inner><field1>inner_value</field1><field2>100</field2></inner></nestedstruct>"
71        );
72    }
73}