summaryrefslogtreecommitdiff
path: root/src/xmlelements.rs
blob: 86d7c7785b5e27841ed64be890903d7aa7c1282d (plain)
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
use ggez::filesystem::File;
use std::io::BufReader;
use xml::reader::{
    EventReader,
    XmlEvent::{self, StartElement},
};

pub struct XMLElements {
    pub events: Vec<XmlEvent>,
}

impl XMLElements {
    pub fn new(file: File) -> XMLElements {
        XMLElements {
            events: EventReader::new(BufReader::new(file))
                .into_iter()
                .map(Result::unwrap)
                .collect(),
        }
    }

    pub fn get_element(&self, element_name: &str) -> XmlEvent {
        self.events
            .clone()
            .into_iter()
            .find(|e| {
                if let StartElement { name, .. } = e {
                    name.local_name == element_name
                } else {
                    false
                }
            })
            .unwrap()
    }

    pub fn get_element_attribute(
        &self,
        element_name: &str,
        attribute_name: &str,
    ) -> Result<usize, ()> {
        let element = self.get_element(element_name);
        if let StartElement { attributes, .. } = element {
            Ok(attributes
                .iter()
                .find(|a| a.name.local_name == attribute_name)
                .unwrap()
                .value
                .parse()
                .unwrap())
        } else {
            Err(())
        }
    }
}