| 1 | # Examples |
| 2 | |
| 3 | The examples have been designed with [`cargo-script`](https://github.com/DanielKeep/cargo-script) in mind. |
| 4 | |
| 5 | Here I'll just give broad overview how to install [`cargo script`] for Rust 1.5. For more details, check out [cargo-script repository](https://github.com/DanielKeep/cargo-script). |
| 6 | |
| 7 | cargo install cargo-script |
| 8 | |
| 9 | |
| 10 | # Token printer |
| 11 | |
| 12 | The basis of xml5ever is its tokenizer and tree builder. Roughly speaking tokenizer |
| 13 | takes input and returns a set of tokens like comment, processing instruction, start |
| 14 | tag, end tag, etc. |
| 15 | |
| 16 | First let's define our dependencies: |
| 17 | |
| 18 | ```toml |
| 19 | [dependencies] |
| 20 | xml5ever = "0.2.0" |
| 21 | tendril = "0.1.3" |
| 22 | ``` |
| 23 | |
| 24 | With dependencies declared, we can now make a simple tokenizer sink. First step is to |
| 25 | define a [`TokenSink`](https://docs.rs/xml5ever/latest/xml5ever/tokenizer/trait.TokenSink.html). [`TokenSink`](https://docs.rs/xml5ever/latest/xml5ever/tokenizer/trait.TokenSink.html) are traits that received stream of [`Tokens`](https://docs.rs/xml5ever/latest/xml5ever/tokenizer/enum.Token.html). |
| 26 | |
| 27 | In our case we'll define a unit struct (i.e. a struct without any fields). |
| 28 | |
| 29 | ```rust |
| 30 | struct SimpleTokenPrinter; |
| 31 | ``` |
| 32 | |
| 33 | To make `SimpleTokenPrinter` a [`TokenSink`](https://docs.rs/xml5ever/latest/xml5ever/tokenizer/trait.TokenSink.html), we need to implement [process_token](https://docs.rs/xml5ever/latest/xml5ever/tokenizer/trait.TokenSink.html#tymethod.process_token) method. |
| 34 | |
| 35 | ```rust |
| 36 | impl TokenSink for SimpleTokenPrinter { |
| 37 | fn process_token(&mut self, token: Token) { |
| 38 | match token { |
| 39 | CharacterTokens(b) => { |
| 40 | println!("TEXT: {}", &*b); |
| 41 | }, |
| 42 | NullCharacterToken => print!("NULL"), |
| 43 | TagToken(tag) => { |
| 44 | println!("{:?} {} ", tag.kind, &*tag.name.local); |
| 45 | }, |
| 46 | ParseError(err) => { |
| 47 | println!("ERROR: {}", err); |
| 48 | }, |
| 49 | PIToken(Pi{ref target, ref data}) => { |
| 50 | println!("PI : <?{} {}?>", &*target, &*data); |
| 51 | }, |
| 52 | CommentToken(ref comment) => { |
| 53 | println!("<!--{:?}-->", &*comment); |
| 54 | }, |
| 55 | EOFToken => { |
| 56 | println!("EOF"); |
| 57 | }, |
| 58 | DoctypeToken(Doctype{ref name, ref public_id, ..}) => { |
| 59 | println!("<!DOCTYPE {:?} {:?}>", &*name, &*public_id); |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | ``` |
| 65 | |
| 66 | Now, we need some input to process. For input we'll use `stdin`. However, xml5ever `tokenize_to` method only takes `StrTendril`. So we need to construct a |
| 67 | [`ByteTendril`](https://docs.rs/tendril/latest/tendril/type.ByteTendril.html) using `ByteTendril::new()`, then read the `stdin` using [`read_to_tendril`](https://docs.rs/tendril/latest/tendril/trait.ReadExt.html#tymethod.read_to_tendril) extension. |
| 68 | |
| 69 | Once that is set, to make `SimpleTokenPrinter` parse the input, call, |
| 70 | `tokenize_to` with it as the first parameter, input wrapped in Option for second parameter and XmlToke. |
| 71 | |
| 72 | ```rust |
| 73 | fn main() { |
| 74 | let sink = SimpleTokenPrinter; |
| 75 | |
| 76 | // We need a ByteTendril to read a file |
| 77 | let mut input = ByteTendril::new(); |
| 78 | // Using SliceExt.read_to_tendril we read stdin |
| 79 | io::stdin().read_to_tendril(&mut input).unwrap(); |
| 80 | // For xml5ever we need StrTendril, so we reinterpret it |
| 81 | // into StrTendril. |
| 82 | // |
| 83 | // You might wonder, how does `try_reinterpret` know we |
| 84 | // need StrTendril and the answer is type inference based |
| 85 | // on `tokenize_xml_to` signature. |
| 86 | let input = input.try_reinterpret().unwrap(); |
| 87 | // Here we create and run tokenizer |
| 88 | let mut tok = XmlTokenizer::new(sink, Default::default()); |
| 89 | // We pass input to parsed. |
| 90 | tok.feed(input); |
| 91 | |
| 92 | // tok.end must be invoked for final bytes to be processed. |
| 93 | tok.end(); |
| 94 | } |
| 95 | ``` |
| 96 | |
| 97 | NOTE: `unwrap` causes panic, it's only OK to use in simple examples. |
| 98 | |
| 99 | For full source code check out: [`examples/simple_xml_tokenizer.rs`](https://github.com/servo/html5ever/blob/main/xml5ever/examples/simple_xml_tokenizer.rs) |
| 100 | |
| 101 | Once we have successfully compiled the example we run the example with inline |
| 102 | xml |
| 103 | |
| 104 | ```bash |
| 105 | cargo script simple_xml_tokenizer.rs <<< "<xml>Text with <b>bold words</b>!</xml>" |
| 106 | ``` |
| 107 | |
| 108 | or by sending an [`examples/example.xml`](https://github.com/servo/html5ever/blob/main/xml5ever/examples/example.xml) located in same folder as examples. |
| 109 | |
| 110 | ```bash |
| 111 | cargo script simple_xml_tokenizer.rs < example.xml |
| 112 | ``` |
| 113 | |
| 114 | # Tree printer |
| 115 | |
| 116 | To actually get an XML document tree from the xml5ever, you need to use a `TreeSink`. |
| 117 | `TreeSink` is in many way similar to the TokenSink. Basically, TokenSink takes data |
| 118 | and returns list of tokens, while TreeSink takes tokens and returns a tree of parsed |
| 119 | XML document. Do note, that this is a simplified explanation and consult |
| 120 | documentation for more info. |
| 121 | |
| 122 | Ok, with that in mind, let's build us a TreePrinter. For example if we get an XML |
| 123 | file like: |
| 124 | |
| 125 | ```xml |
| 126 | <student> |
| 127 | <first-name>Bobby</first-name> |
| 128 | <last-name>Tables</last-name> |
| 129 | </student> |
| 130 | ``` |
| 131 | |
| 132 | We'd want a structure similar to this: |
| 133 | |
| 134 | ``` |
| 135 | #document |
| 136 | student |
| 137 | first-name |
| 138 | #text Bobby |
| 139 | last-name |
| 140 | #text Tables |
| 141 | |
| 142 | ``` |
| 143 | We won't print anything other than element names and text fields. So comments, |
| 144 | doctypes and other such elements are ignored. |
| 145 | |
| 146 | First part is similar to making SimpleTokenPrinter: |
| 147 | |
| 148 | ```rust |
| 149 | // We need to allocate an input tendril for xml5ever |
| 150 | let mut input = ByteTendril::new(); |
| 151 | // Using SliceExt.read_to_tendril functions we can read stdin |
| 152 | io::stdin().read_to_tendril(&mut input).unwrap(); |
| 153 | let input = input.try_reinterpret().unwrap(); |
| 154 | ``` |
| 155 | |
| 156 | This time, we need an implementation of [`TreeSink`](https://docs.rs/xml5ever/latest/xml5ever/tree_builder/trait.TreeSink.html). xml5ever comes with a |
| 157 | built-in `TreeSink` implementation called [`RcDom`](https://docs.rs/markup5ever_rcdom/latest/markup5ever_rcdom/struct.RcDom.html). To process input into |
| 158 | a `TreeSink` we use the following line: |
| 159 | |
| 160 | ```rust |
| 161 | let dom: RcDom = parse(one_input(input), Default::default()); |
| 162 | ``` |
| 163 | |
| 164 | Let's analyze it a bit. First there is `let dom: RcDom`. We need this part, |
| 165 | because the type inferencer can't infer which TreeSink implementation we mean |
| 166 | in this scenario. |
| 167 | |
| 168 | Function [`one_input`](https://ygg01.github.io/docs/xml5ever/xml5ever/fn.one_input.html) is a convenience function that turns any value into an iterator. In this case |
| 169 | it converts a StrTendril into an Iterator over itself. |
| 170 | |
| 171 | Ok, so now that we parsed our tree what with it? Well, for that we might need some |
| 172 | kind of function that will help us traverse it. We shall call that function `walk`. |
| 173 | |
| 174 | ```rust |
| 175 | fn walk(prefix: &str, handle: Handle) { |
| 176 | let node = handle.borrow(); |
| 177 | |
| 178 | // We print out the prefix before we start |
| 179 | print!("{}", prefix); |
| 180 | // We are only interested in following nodes: |
| 181 | // Document, Text and Element, so our match |
| 182 | // reflects that. |
| 183 | match node.node { |
| 184 | Document |
| 185 | => println!("#document"), |
| 186 | |
| 187 | Text(ref text) => { |
| 188 | println!("#text {}", text.escape_default()) |
| 189 | }, |
| 190 | |
| 191 | Element(ref name, _) => { |
| 192 | println!("{}", name.local); |
| 193 | }, |
| 194 | |
| 195 | _ => {}, |
| 196 | |
| 197 | } |
| 198 | |
| 199 | // We increase indent in child nodes |
| 200 | let new_indent = { |
| 201 | let mut temp = String::new(); |
| 202 | temp.push_str(prefix); |
| 203 | temp.push_str(" "); |
| 204 | temp |
| 205 | }; |
| 206 | |
| 207 | for child in node.children.iter() |
| 208 | // In order to avoid weird indentation, we filter |
| 209 | // only Text/Element nodes. |
| 210 | // We don't need to filter Document since its guaranteed |
| 211 | // child elements don't contain documents |
| 212 | .filter(|child| match child.borrow().node { |
| 213 | Text(_) | Element (_, _) => true, |
| 214 | _ => false, |
| 215 | } |
| 216 | ) { |
| 217 | // Recursion - Yay! |
| 218 | walk(&new_indent, child.clone()); |
| 219 | } |
| 220 | } |
| 221 | ``` |
| 222 | |
| 223 | For full source code check out: [`examples/xml_tree_printer.rs`](https://github.com/servo/html5ever/blob/main/rcdom/examples/xml_tree_printer.rs) |