docx_reader/reader/
hyperlink.rs

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
use std::io::Read;
use std::str::FromStr;
use xml::attribute::OwnedAttribute;
use xml::reader::{EventReader, XmlEvent};

use super::*;

impl ElementReader for Hyperlink {
	fn read<R: Read>(
		r: &mut EventReader<R>,
		attrs: &[OwnedAttribute],
	) -> Result<Self, ReaderError> {
		let mut rid: Option<String> = read(attrs, "id");
		let mut anchor: Option<String> = read(attrs, "anchor");
		let history: Option<String> = read(attrs, "history");
		let mut link = Hyperlink {
			link: if anchor.is_some() {
				HyperlinkData::Anchor {
					anchor: anchor.take().unwrap(),
				}
			} else {
				HyperlinkData::External {
					rid: rid.take().unwrap_or_default(),
					path: String::default(), // not used
				}
			},
			history: history.map(|h| usize::from_str(&h).unwrap_or(1)),
			children: vec![],
		};

		loop {
			let e = r.next();
			match e {
				Ok(XmlEvent::StartElement {
					attributes, name, ..
				}) => {
					let e = XMLElement::from_str(&name.local_name).unwrap();

					match e {
						XMLElement::Run => {
							if let Ok(run) = Run::read(r, attrs) {
								link = link.add_run(run);
							}
							continue;
						}
						XMLElement::Insert => {
							if let Ok(ins) = Insert::read(r, &attributes) {
								link = link.add_insert(ins);
							}
							continue;
						}
						XMLElement::Delete => {
							if let Ok(del) = Delete::read(r, &attributes) {
								link = link.add_delete(del);
							}
							continue;
						}
						_ => {}
					}
				}
				Ok(XmlEvent::EndElement { name, .. }) => {
					let e = XMLElement::from_str(&name.local_name).unwrap();
					if e == XMLElement::Hyperlink {
						return Ok(link);
					}
				}
				Err(_) => return Err(ReaderError::XMLReadError),
				_ => {}
			}
		}
	}
}