Thanks to visit codestin.com
Credit goes to docs.rs

html_parser/dom/
element.rs

1use super::node::Node;
2use super::span::SourceSpan;
3use serde::{Serialize, Serializer};
4use std::collections::{BTreeMap, HashMap};
5use std::default::Default;
6use std::result::Result;
7
8/// Normal: `<div></div>` or Void: `<meta/>`and `<meta>`
9#[derive(Debug, Clone, Serialize, PartialEq)]
10#[serde(rename_all = "camelCase")]
11// TODO: Align with: https://html.spec.whatwg.org/multipage/syntax.html#elements-2
12pub enum ElementVariant {
13    /// A normal element can have children, ex: <div></div>.
14    Normal,
15    /// A void element can't have children, ex: <meta /> and <meta>
16    Void,
17}
18
19pub type Attributes = HashMap<String, Option<String>>;
20
21/// Most of the parsed html nodes are elements, except for text
22#[derive(Debug, Clone, Serialize, PartialEq)]
23#[serde(rename_all = "camelCase")]
24pub struct Element {
25    /// The id of the element
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub id: Option<String>,
28
29    /// The name / tag of the element
30    pub name: String,
31
32    /// The element variant, if it is of type void or not
33    pub variant: ElementVariant,
34
35    /// All of the elements attributes, except id and class
36    #[serde(skip_serializing_if = "HashMap::is_empty")]
37    #[serde(serialize_with = "ordered_map")]
38    pub attributes: Attributes,
39
40    /// All of the elements classes
41    #[serde(skip_serializing_if = "Vec::is_empty")]
42    pub classes: Vec<String>,
43
44    /// All of the elements child nodes
45    #[serde(skip_serializing_if = "Vec::is_empty")]
46    pub children: Vec<Node>,
47
48    /// Span of the element in the parsed source
49    #[serde(skip)]
50    pub source_span: SourceSpan
51}
52
53impl Default for Element {
54    fn default() -> Self {
55        Self {
56            id: None,
57            name: "".to_string(),
58            variant: ElementVariant::Void,
59            classes: vec![],
60            attributes: HashMap::new(),
61            children: vec![],
62            source_span: SourceSpan::default()
63        }
64    }
65}
66
67fn ordered_map<S: Serializer>(value: &Attributes, serializer: S) -> Result<S::Ok, S::Error> {
68    let ordered: BTreeMap<_, _> = value.iter().collect();
69    ordered.serialize(serializer)
70}