docx_rs/reader/
hyperlink.rs1use std::io::Read;
2use std::str::FromStr;
3
4use super::*;
5
6use super::attributes::*;
7
8impl ElementReader for Hyperlink {
9 fn read<R: Read>(
10 r: &mut EventReader<R>,
11 attrs: &[OwnedAttribute],
12 ) -> Result<Self, ReaderError> {
13 let mut rid: Option<String> = read(attrs, "id");
14 let mut anchor: Option<String> = read(attrs, "anchor");
15 let history: Option<String> = read(attrs, "history");
16 let mut link = Hyperlink {
17 link: if anchor.is_some() {
18 HyperlinkData::Anchor {
19 anchor: anchor.take().unwrap(),
20 }
21 } else {
22 HyperlinkData::External {
23 rid: rid.take().unwrap_or_default(),
24 path: String::default(), }
26 },
27 history: history.map(|h| usize::from_str(&h).unwrap_or(1)),
28 children: vec![],
29 };
30
31 loop {
32 let e = r.next();
33 match e {
34 Ok(XmlEvent::StartElement {
35 attributes, name, ..
36 }) => {
37 let e = XMLElement::from_str(&name.local_name).unwrap();
38
39 match e {
40 XMLElement::Run => {
41 if let Ok(run) = Run::read(r, attrs) {
42 link = link.add_run(run);
43 }
44 continue;
45 }
46 XMLElement::Insert => {
47 if let Ok(ins) = Insert::read(r, &attributes) {
48 link = link.add_insert(ins);
49 }
50 continue;
51 }
52 XMLElement::Delete => {
53 if let Ok(del) = Delete::read(r, &attributes) {
54 link = link.add_delete(del);
55 }
56 continue;
57 }
58 XMLElement::BookmarkStart => {
59 if let Ok(s) = BookmarkStart::read(r, &attributes) {
60 link = link.add_bookmark_start(s.id, s.name);
61 }
62 continue;
63 }
64 XMLElement::BookmarkEnd => {
65 if let Ok(e) = BookmarkEnd::read(r, &attributes) {
66 link = link.add_bookmark_end(e.id);
67 }
68 continue;
69 }
70 XMLElement::CommentRangeStart => {
71 if let Some(id) = read(&attributes, "id") {
72 if let Ok(id) = usize::from_str(&id) {
73 let comment = Comment::new(id);
74 link = link.add_comment_start(comment);
75 }
76 }
77 continue;
78 }
79 XMLElement::CommentRangeEnd => {
80 if let Some(id) = read(&attributes, "id") {
81 if let Ok(id) = usize::from_str(&id) {
82 link = link.add_comment_end(id);
83 }
84 }
85 continue;
86 }
87 _ => {}
88 }
89 }
90 Ok(XmlEvent::EndElement { name, .. }) => {
91 let e = XMLElement::from_str(&name.local_name).unwrap();
92 if e == XMLElement::Hyperlink {
93 return Ok(link);
94 }
95 }
96 Err(_) => return Err(ReaderError::XMLReadError),
97 _ => {}
98 }
99 }
100 }
101}