diet-xml 0.2.2

Probably the simplest, most approachable XML builder for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
// use crate::schema::XmlSchema;
use crate::schema::XmlSchema;
use std::fmt::Write;
use std::collections::HashMap;

#[derive(Debug)]
struct Element {
        position: Vec<usize>,
        value: String,       
        cdata: bool,
         
}


pub(crate) struct Builder {
    elements: Vec<Element>,
    schema: XmlSchema,
    current_key: Vec<usize>,
    //lookup  String value of key, must be unique to (no_element, no_unique_key)
    key_list: HashMap::<(usize,String),usize>,
    key_count: usize,
    pub xml_output: String,
    attribute_list: HashMap::<(usize,usize),String>,

    headers: Vec<String>,
    ind_original_header: bool,

    
    
}

pub struct ChainFromAdd<'a>
{
    builder: &'a mut Builder,
    no_element: usize,
    no_key: usize


}

impl<'a> ChainFromAdd<'a> {
    pub(crate) fn attributes(self, attributes: &[(&str, &str)]) {
        // Build all attributes from the pair values
        let mut all_attributes = String::new();
        for &(att, value) in attributes {
            write!(all_attributes, " {}=\"{}\"", att, value).unwrap();
        }

        match self.builder.attribute_list.get(&(self.no_element, self.no_key)) {
            Some(value) => {
                if &all_attributes != value {
                    panic!("Tried to add a second set of attributes to the same key/element");
                }
                // Same attributes added again are just ignored and okay
            }
            None => {
                self.builder
                    .attribute_list
                    .insert((self.no_element, self.no_key), all_attributes.clone());
            }
        }
    }
    
    pub fn attribute<V: ToString>(self, name: &str, value: V) {
        // Build a single attribute as a pair, accepting any value that implements ToString
        let mut all_attributes = String::new();
        let value_quoted = format!("\"{}\"", value.to_string());
        let combined = format!(" {}={}", name, value_quoted);
        all_attributes.push_str(&combined);
        match self.builder.attribute_list.get(&(self.no_element, self.no_key)) {
            Some(existing) => {
                if &all_attributes != existing {
                    panic!("Tried to add a second set of attributes to the same key/element");
                }
                // same added again is just ignored and ok
            },
            None => {
                self.builder.attribute_list.insert((self.no_element, self.no_key), all_attributes.clone());
            }
        }
    }

    pub fn cdata(self) -> Self {
       
        self.builder.elements.last_mut().unwrap().cdata = true;
        self
    }
}










impl Builder {


    
    pub(crate) fn clear_headers(&mut self) {
        self.headers.clear();
    }

    pub(crate) fn custom_header(&mut self, headers: &str) {
        if self.ind_original_header == true
        {       self.headers.clear(); }
        self.headers.push(format!("<?{}?>", headers));
        self.ind_original_header = false;
    }



     pub(crate) fn new() -> Self
    {   
       
        Self {
         elements: vec![Element { position: Vec::new(), value: "".to_string(), cdata: false }],
         schema:  XmlSchema::new(),
         current_key: Vec::new(),
         key_list: HashMap::new(),
         key_count: 0,
         xml_output: String::new(),
         attribute_list: HashMap::new(),
         headers: vec!["<?xml version=\"1.0\" encoding=\"UTF-8\"?>".to_string()],
            ind_original_header: true,
        }
    }

    pub(crate) fn set_schema(&mut self,txt_schema: &str)
    {
        self.schema.set_schema(txt_schema);
        self.schema.parse_schema();
        self.current_key.resize(self.schema.element_no_lookup.len(), 0);
    }

    pub(crate) fn get_position(&self,nm_element: &str) -> &Vec<usize>
    {
     self.schema.element_no_lookup
    .get(nm_element)
    .expect("Tried to add an element that does not exist in the schema")
    }


        
 #[allow(unused_must_use)]   
    pub(crate) fn set_key(&mut self, nm_element: &str, txt_key: &str) -> ChainFromAdd {
        let position = self.get_position(nm_element);
        let &no_element = position.last().unwrap();
        let returned_key: usize;
        if let Some(&existing) = self.key_list.get(&(no_element, txt_key.to_string())) {
            self.current_key[no_element] = existing;
            returned_key = existing;
        } else {
            self.key_count += 1;
            self.key_list.insert((no_element, txt_key.to_string()), self.key_count);
            self.current_key[no_element] = self.key_count;
            returned_key = self.key_count;
        }
        ChainFromAdd { builder: self, no_element, no_key: returned_key }
    }

      

    pub(crate) fn clear_key(&mut self)
    {
        self.current_key.fill(0)  ;
    }

    #[allow(unused_must_use)]
    pub(crate) fn add_element(&mut self, nm_element: &str, value_element: &str) -> ChainFromAdd {
        self.key_count += 1;
        let key_count = self.key_count;
        let final_value = if value_element.is_empty() {
            " ".to_string()
        } else {
            value_element.to_string()
        };
        let (positition_and_key, element_number) = {
            let position = self.get_position(nm_element);
            (create_position(&position, &self.current_key), *position.last().unwrap())
        };
        self.elements.push(Element { position: positition_and_key, value: final_value, cdata: false });
        ChainFromAdd { builder: self, no_element: element_number, no_key: key_count }
    }

    // combines position and key into a combined alternative Vec, this is what is sorted at teh end to create the final output

    pub(crate) fn build_xml(&mut self)
    {
    
    for i in &self.headers {
        write!(self.xml_output, "{}\n", i).unwrap();
    }

     for i in &mut self.schema.element_names {
    *i = i.split('!').next().unwrap().to_string();
    }
        // add dummy row at end to enable last lags to be closed off
        // sort so element are all groups together , ordered by elements and keys
        self.elements.sort_unstable_by(|a, b| a.position.cmp(&b.position));
        self.elements.push(Element { position: Vec::new(), value: "".to_string(), cdata: false });

        let mut opening_tags: Vec<(usize,usize,usize)> = Vec::new();
for n in 1..self.elements.len() {
    let last = &self.elements[n - 1];
    let current =  &self.elements[n];
   // println!("Last element is: {:?}",last);
   // println!("Current element is: {:?}",current);

    let len = last.position.len().max(current.position.len());

    // used to stored information for opening tags on pass through closing tags
    // (no_element, no_key, i (depth))
    
    opening_tags.clear();
    
    for i in (0..len/2).rev()  {
    
    
    let l = (last.position.get(2*i),last.position.get(2*i+1));     
    let c = (current.position.get(2*i),current.position.get(2*i+1));    

   // println!("Last pair is: {:?}",l);
  //  println!("Current pair is: {:?}",c);

    if l != c && l.0 != None {
   
        let elem_name = &self.schema.element_names[*l.0.unwrap()];
    
        let indent = if i == last.position.len()/2 - 1 {
    "".to_string()
} else {
    "  ".repeat(i)
};
          
   
       
         write!(self.xml_output, "{}</{}>\n", indent, elem_name).unwrap();
   // print!("{}", open_tag);
  
    } 
        //record opening tags on same pass through
        if l != c && c.0 != None {  opening_tags.push((*c.0.unwrap(),*c.1.unwrap(),i)) ;   }    
  
    } 

        // opening tags need to open from lowest level upwards so we need to iterate in reverse

       for &n in opening_tags.iter().skip(1).rev() {
  
      let elem_name = &self.schema.element_names[n.0];


     // fetch any attribute associated with the element,key combination else
     let attribute = self.attribute_list.get(&(n.0,n.1)) ;

     

    let open_tag = format!("{}<{}{}>\n", "  ".repeat(n.2),  elem_name, attribute.unwrap_or(&"".to_string()));
     self.xml_output.push_str(&open_tag);
   // print!("{}", open_tag);
}

// After printing all opening tags, print the value (if any)
// the check is necessary due to the last dummy element, maybe change this later on
if !current.value.is_empty() {
    let elem_name = &self.schema.element_names[opening_tags[0].0];
    let attribute = &self.attribute_list.get(&(opening_tags[0].0,opening_tags[0].1))  ;

    if self.elements[n].cdata {
        write!(
            self.xml_output,
            "{}<{}{}><![CDATA[{}]]>",
            "  ".repeat(opening_tags.first().unwrap().2),
            elem_name,
            attribute.unwrap_or(&"".to_string()),
            self.elements[n].value
            
        ).unwrap();
    } else {
        write!(
            self.xml_output,
            "{}<{}{}>{}",
            "  ".repeat(opening_tags.first().unwrap().2),
            elem_name,
            attribute.unwrap_or(&"".to_string()),
            escape_xml(&self.elements[n].value)
            
        ).unwrap();
    }
  // self.xml_output.push_str(&open_tag);
   // print!("{}", open_tag);
}


    }


    }
}


fn escape_xml(input: &str) -> String {
    let mut escaped = String::with_capacity(input.len());
    for c in input.chars() {
        match c {
            '&' => escaped.push_str("&amp;"),
            '<' => escaped.push_str("&lt;"),
            '>' => escaped.push_str("&gt;"),
            '"' => escaped.push_str("&quot;"),
            '\'' => escaped.push_str("&apos;"),
            _ => escaped.push(c),
        }
    }
    escaped
}




 fn create_position(position: &Vec<usize>, key: &Vec<usize>) -> Vec<usize> {
    let len = position.len().max(key.len());
    let mut combined = Vec::with_capacity(len * 2);
    for i in position {
        
        let key_val = *key.get(*i).unwrap();
        // Combine however you want; here, for example, just sum:
        combined.push(*i);
        combined.push(key_val);
        // Or if you want to keep both, you could push one or the other, etc.
    }
    combined
}





#[cfg(test)]
mod tests {
    use super::*;
/*/
   //#[test]
   // changed functionality invalid test
    fn test_create_position()
    {
        //placehodler
        // update this test now an key list of all elements is used rather than
        // just level depth keys
        let position: Vec<usize> = [1,2,3,4,5,6].to_vec(); 
        let key: Vec<usize> = [0,1,2,3,4].to_vec();

        let combined  =  create_position(&position, &key);

        assert_eq!(combined,[1,0,2,1,3,2,4,3,5,4,6,0].to_vec() )

    }
*/
    #[test]
    fn test_set_key()
    {
        let mut xb: Builder = Builder::new();
        xb.set_schema(
            "<root>
                        <g1></g1>
                        <g2><g3><g4></g4></g3></g2></root>");
        
           for i in  &xb.schema.element_no_lookup
        {
            println!("{:?}",i);
        }
        xb.set_key("g2", "1");     
        println!("{:?}",xb.current_key);
        xb.set_key("g2", "1");
        println!("{:?}",xb.current_key);
        xb.set_key("g2", "2");
        println!("{:?}",xb.current_key);

        xb.set_key("g1", "1");     
        println!("{:?}",xb.current_key);
        xb.set_key("g1", "1");
        println!("{:?}",xb.current_key);
        xb.set_key("g1", "2");
        println!("{:?}",xb.current_key);

        xb.set_key("g2", "3");
        println!("{:?}",xb.current_key);
        xb.set_key("g2", "4");
        println!("{:?}",xb.current_key);

        xb.set_key("g4", "1");
        println!("{:?}",xb.current_key);

        xb.set_key("root", "0");
        println!("{:?}",xb.current_key);

        xb.add_element("g4", "999");
        println!("{:?}",xb.elements[0] );

        xb.clear_key();
        println!("{:?}",xb.current_key);


        xb.build_xml();
       



    }


}