basic_usage/
basic_usage.rs

1use diet_xml::XmlBuilder;
2
3fn main() {
4
5
6    // example data
7    let employees = vec![
8        Employee { id: 1, first: "John", last: "Doe", dob: "1900-01-01" },
9        Employee { id: 2, first: "Jane", last: "Doe", dob: "1800-12-31" },
10        Employee { id: 3, first: "John", last: "Dough", dob: "1700-01-01" },
11     
12    ];
13
14    // create an XmlBuilder struct
15
16    // this is an struct that allows you build an xml output in memory
17    let mut xb = XmlBuilder::new();
18    
19    // define the schema you wish to populate in plain text
20    xb.set_schema("
21    <root>
22        <employee>
23            <name>
24                <first></first>
25                <last></last>
26            </name>
27            <info>
28                <dob></dob>
29            </info>
30        </employee>
31        <passing_str_ok></passing_str_ok>
32        <passing_i32_ok></passing_i32_ok>
33        <name!2></name!2>   
34    </root>");
35
36    // default header is <?xml version="1.0" encoding="UTF-8"?>
37    // to add custom headers, multiple allowed use
38    // xb.set_header("your customer header, < > will be applied the the star/end automatically");
39
40    for e in employees{
41
42     
43        // set element used to group to parent elements
44        xb.set_key("employee", e.id)
45            .attribute("id", e.id);
46
47          // unlike other libraries the parent elements are implicitly built
48        xb.add_element("first", e.first);
49        xb.add_element("last", e.last);
50
51        // you can chain into the cdata() method to enclose an element in cdata tags
52        xb.add_element("dob", e.dob).cdata();
53
54        // clears current key context
55        xb.clear_keys();       
56   }
57
58
59    // values can be passed as ny type implementing to_string()
60    xb.add_element("passing_str_ok", "some str");
61    xb.add_element("passing_i32_ok", 111222333);
62
63    // duplicate element names should be distinguised by !AnyAlphaNumtext in the schema definition
64    xb.add_element("name!2", "suffix !2 has been removed, this enables use of duplicate element names");
65
66   // builds the xml in the background
67   xb.build_xml();
68
69
70    // function .xml_out() returns string of the xml output
71    println!("{}", xb.xml_out());
72}
73
74
75
76
77struct Employee {
78    id: usize,
79    first: &'static str,
80    last: &'static str,
81    dob: &'static str,
82}