node_html_parser/dom/element/
serialize.rs1use super::main::HTMLElement; use super::normalize_attr_quotes; impl HTMLElement {
5 pub fn outer_html(&self) -> String {
6 if self.is_root() {
7 return self.inner_html();
8 } let tag = self.name();
10 let attrs = if self.raw_attrs.is_empty() {
11 String::new()
12 } else {
13 format!(" {}", self.raw_attrs.trim())
14 };
15 if self.is_void {
16 if self.void_add_slash {
17 let mut norm_attrs = if attrs.is_empty() {
23 String::new()
24 } else {
25 normalize_attr_quotes(&attrs)
26 };
27 if !norm_attrs.is_empty() {
29 let mut converted = String::with_capacity(norm_attrs.len());
30 let nb = norm_attrs.as_bytes();
31 let mut i = 0;
32 while i < nb.len() {
33 let c = nb[i] as char;
34 if c == '\'' {
35 converted.push(c);
37 i += 1;
38 continue;
39 }
40 if c == '=' && i + 1 < nb.len() && nb[i + 1] as char == '\'' {
42 converted.push('=');
43 converted.push('"');
44 i += 2; let start = i;
46 while i < nb.len() && nb[i] as char != '\'' {
47 i += 1;
48 }
49 let val = &norm_attrs[start..i];
50 if val.contains('"') {
52 converted.push('\'');
53 converted.push_str(val);
54 converted.push('\'');
55 } else {
56 converted.push_str(val);
57 converted.push('"');
58 }
59 if i < nb.len() && nb[i] as char == '\'' {
60 i += 1;
61 }
62 continue;
63 }
64 converted.push(c);
65 i += 1;
66 }
67 norm_attrs = converted;
68 }
69 if norm_attrs.is_empty() {
70 format!("<{}{}{}>", tag, norm_attrs, "/")
71 } else if norm_attrs.ends_with(' ') {
72 format!("<{}{}{}>", tag, norm_attrs, "/")
73 } else {
74 format!("<{}{} {}>", tag, norm_attrs, "/")
75 }
76 } else {
77 let norm_attrs = if attrs.is_empty() {
78 String::new()
79 } else {
80 normalize_attr_quotes(&attrs)
81 };
82 format!("<{}{}>", tag, norm_attrs)
83 }
84 } else {
85 let norm_attrs = if attrs.is_empty() {
87 String::new()
88 } else {
89 normalize_attr_quotes(&attrs)
90 };
91 let auto_closed_empty = match self.range() {
94 Some((s, e)) if s == e && self.children.is_empty() => true,
95 _ => false,
96 };
97 if auto_closed_empty {
98 format!("<{}{}>", tag, norm_attrs)
99 } else {
100 format!("<{}{}>{}</{}>", tag, norm_attrs, self.inner_html(), tag)
101 }
102 }
103 }
104 pub fn to_string(&self) -> String {
106 self.outer_html()
107 }
108}