O'Reilly logo

Developing Web Applications with Haskell and Yesod by Michael Snoyman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Cursor

Suppose you want to pull the title out of an XHTML document. You could do so with the Text.XML interface we just described, using standard pattern matching on the children of elements. But that would get very tedious, very quickly. Probably the gold standard for these kinds of lookups is XPath, where you would be able to write /html/head/title. And that’s exactly what inspired the design of the Text.XML.Cursor combinators.

A cursor is an XML node that knows its location in the tree; it’s able to traverse upwards, sideways, and downwards. (Under the surface, this is achieved by tying the knot.) There are two functions available for creating cursors from Text.XML types: fromDocument and fromNode.

We also have the concept of an Axis, defined as type Axis = Cursor -> [Cursor]. It’s easiest to get started by looking at example axes: child returns zero or more cursors that are the child of the current one, parent returns the single parent cursor of the input, or an empty list if the input is the root element, and so on.

In addition, there are some axes that take predicates. element is a commonly used function that filters down to only elements that match the given name. For example, element "title" will return the input element if its name is “title,” or an empty list otherwise.

Another common function which isn’t quite an axis is content :: Cursor -> [Text]. For all content nodes, it returns the contained text; otherwise, it returns an empty list.

And thanks to the monad instance for ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required