glexml/selector
CSS selectors for glexml documents.
import glexml
import glexml/selector
let assert Ok(document) = glexml.parse(opf_source)
selector.select(document.root, "manifest > item[properties~=nav]")
// -> Ok([the nav item])
Supported syntax:
- Type selectors and the universal selector:
item,* - Attribute selectors:
[href],[rel=next],[properties~=nav],[lang|=en],[href^=http],[href$=.xhtml],[href*=chapter] - Class and ID shorthands, by the usual XML convention:
.titlemeans[class~=title]and#tocmeans[id=toc] - Combinators: descendant (
nav a), child (spine > itemref), adjacent sibling (h1 + p), general sibling (h1 ~ p) - Selector lists:
metadata, manifest - Pseudo-classes:
:first-child,:last-child,:only-child,:empty,:root,:nth-child(2)/(odd)/(even)/(2n+1), and:not(...)with a list of compound selectors
XML-specific behaviour, since names here are literal strings rather than resolved namespaces:
- Matching is case-sensitive throughout, as XML requires.
- A plain name matches exactly, prefix included:
titledoes not matchdc:title. dc|titlematches the literal qualified namedc:title(the prefix as written in the document, not a namespace URI).|titleand*|titlematch any element with local nametitle, whatever its prefix.- The same applies to attribute names, where a literal colon is also
accepted:
[epub|type=toc]and[epub:type=toc]are equivalent.
Types
A parsed selector, ready to be matched. Parse one with parse and reuse
it across as many queries as you like.
pub opaque type Selector
A problem found while parsing a selector string.
pub type SelectorError {
EmptySelector
UnexpectedEndOfSelector
UnexpectedCharacter(character: String)
UnknownPseudoClass(name: String)
InvalidNth(argument: String)
}
Constructors
-
EmptySelector -
UnexpectedEndOfSelector -
UnexpectedCharacter(character: String) -
UnknownPseudoClass(name: String) -
InvalidNth(argument: String)
Values
pub fn error_to_string(error: SelectorError) -> String
Convert a SelectorError into a human readable message.
pub fn matches(
element: glexml.Element,
selector: Selector,
) -> Bool
Whether the element itself matches the selector, treating it as the root of its own tree.
pub fn query(
element: glexml.Element,
selector: Selector,
) -> List(glexml.Element)
Find every element in the tree matching the selector, in document order.
The given element is part of the tree being searched, so query(root, ":root") returns the root itself.
pub fn query_first(
element: glexml.Element,
selector: Selector,
) -> Result(glexml.Element, Nil)
Find the first element in document order matching the selector.
pub fn select(
element: glexml.Element,
selector: String,
) -> Result(List(glexml.Element), SelectorError)
Parse and run a selector in one step. Prefer parse + query when the
same selector is used repeatedly.