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
extern crate xml;
use core::borrow::Borrow;
use std::fmt::Error;
use std::fs;
use std::fs::File;
use std::io::{BufReader, Read};
use std::thread::park;
use xml::reader::{EventReader, XmlEvent};
use self::xml::attribute::OwnedAttribute;
#[derive(Clone, Debug)]
pub struct Element {
pub tag: String,
pub data: String,
pub attributes: Vec<OwnedAttribute>,
pub childs: Vec<Element>,
}
impl Element {
pub fn reset(&mut self) {
self.tag.clear();
self.data.clear();
self.attributes.clear();
self.childs.clear();
}
pub fn get_attr(&self, arg: &str) -> String {
for x in &self.attributes {
if x.name.to_string().as_str() == arg {
return x.value.clone();
}
}
return "".to_string();
}
}
pub fn load_xml(file_content: &str) -> Vec<Element> {
let parser = EventReader::from_str(file_content);
return parser_func(parser);
}
fn parser_func(parser: EventReader<&[u8]>) -> Vec<Element> {
let mut depth = 0;
let mut temp_element = &mut Element {
tag: "".to_string(),
data: "".to_string(),
attributes: vec![],
childs: vec![],
};
let mut fathers = vec![];
for item in parser {
match item {
Ok(XmlEvent::StartElement { name, attributes, .. }) => {
temp_element.tag = name.local_name;
temp_element.attributes = attributes.clone();
&fathers.push(temp_element.clone());
depth += 1;
}
Ok(XmlEvent::Characters(data)) => {
let last = fathers.last_mut().unwrap();
(*last).childs.push(Element {
tag: "".to_string(),
data: " ".to_string() + data.clone().replace("\r", "").replace("\n", "").trim(),
attributes: vec![],
childs: vec![],
})
}
Ok(XmlEvent::EndElement { name }) => {
let pop = fathers.pop().unwrap();
let last = fathers.last_mut();
if last.is_some() {
last.unwrap().childs.push(pop);
} else {
fathers.push(pop)
}
temp_element.reset();
depth -= 1;
}
Err(e) => {
println!("Error: {},{}", e, temp_element.tag);
break;
}
_ => {}
}
}
return fathers;
}
#[test]
fn test_load_file() {
let file_path = "./src/example/Example_ActivityMapper.xml";
println!(">>>>>>>>>>>>>>>>>>>>>>start load {} >>>>>>>>>>>>>>>>>>>>>>>", file_path);
let content = fs::read_to_string(file_path).unwrap();
println!("With text:/n{}", content);
}
#[test]
fn test_load_xml() {
let file_path = "./src/example/Example_ActivityMapper.xml";
println!(">>>>>>>>>>>>>>>>>>>>>>start load {} >>>>>>>>>>>>>>>>>>>>>>>", file_path);
let content = fs::read_to_string("./src/example/Example_ActivityMapper.xml").unwrap();
println!("With text:/n{}", content);
load_xml(content.as_str());
}