Skip to main content

Crate domtree

Crate domtree 

Source
Expand description

§dom-tree-rs

A tiny, zero-dependency, forgiving HTML parser. It turns messy real-world HTML into a clean DOM tree (and JSON) and never panics on bad input — ideal for the browser, the edge, or anywhere you don’t want to pull in a 100 KB+ parser.

It is not a spec-compliant WHATWG parser (see html5ever for that) and not a speed record (see tl). It is the smallest way to get a usable tree out of arbitrary HTML.

§Quick start

let dom = domtree::parse(r#"<ul id="list"><li class="item">Item 1</li></ul>"#);

let li = dom.find_by_tag("li").next().unwrap();
assert_eq!(li.attr("class"), Some("item"));
assert_eq!(li.text_content(), "Item 1");

// The first list element:
let ul = dom.root().unwrap();
assert_eq!(ul.tag_name(), Some("ul"));
assert_eq!(ul.children().count(), 1);

§What it handles

Void elements (<br>, <img>, …), self-closing tags, comments, doctypes, CDATA, raw text (<script>/<style>), boolean and unquoted attributes, hyphenated/custom tags, common HTML entities, and the everyday “forgot a closing tag” cases (<li>, <p>, table cells, …) via implicit closing.

§What it deliberately does not do

Full WHATWG tree construction: no adoption-agency algorithm, no automatic <html>/<head>/<body> insertion, no foster parenting. Anything it has to recover from is recorded in Dom::errors.

§Features

  • json (default) — the zero-dependency Dom::to_json serializer.
  • serde — optional serde::Serialize for the tree (adds the serde dep).
  • query — a small CSS-selector engine, Dom::select.
  • std — adds std-only conveniences; the crate is no_std + alloc by default.

Structs§

Descendants
Pre-order descendant iterator (see NodeRef::descendants).
Dom
A parsed HTML document: an arena of nodes, a single string buffer they reference, the top-level (root) nodes, and any recovery diagnostics.
NodeId
A handle to a node inside a Dom. Cheap (Copy) and stable for the lifetime of the tree.
NodeRef
A lightweight, Copy read handle to a single node, bound to its Dom.
ParseError
A single recoverable problem encountered while parsing, with the byte offset into the source where it occurred.
Tokenizer
A streaming HTML tokenizer. Construct with Tokenizer::new (or the top-level crate::tokenize) and iterate to get Tokens.

Enums§

AttrValue
The value side of an attribute.
ErrorKind
The category of a ParseError.
NodeKind
What a node is — a borrowed, Copy view returned by NodeRef::kind.
Token
A single lexical token of HTML.

Functions§

parse
Parse a full HTML document into a best-effort tree.
parse_fragment
Parse an HTML fragment.
tokenize
Create a streaming Tokenizer over html without building a tree.