Default instances

NodeDecoder

Basic types

The following types have NodeDecoder instances available out of the box:

java.util.Date

There also is a default NodeDecoder instance available for Date, but this one is slightly more complicated. There are so many different ways of writing dates that there is no reasonable default behaviour - one might argue that defaulting to ISO 8601 might make sense, but there doesn’t appear to be a sane way of implementing that in Java’s crusty date / time API.

Instead of providing a default implementation that is likely going to be incorrect for most people, kantan.xpath provides easy tools for creating decoders from an instance of DateFormat.

We could for example declare a decoder for something ISO 8601-like:

import kantan.xpath.implicits._
import kantan.xpath.NodeDecoder
import java.util.{Locale, Date}

implicit val decoder: NodeDecoder[Date] = NodeDecoder.dateDecoder(new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH))

And we’re now capable of decoding XML content as dates:

"<date>2000-01-00T00:00:00.000</date>".evalXPath[Date](xp"/date")
// res0: kantan.xpath.package.XPathResult[Date] = Right(
//   value = Fri Dec 31 00:00:00 CET 1999
// )

Either

For any two types A and B that each have a NodeDecoder, there exists a NodeDecoder[Either[A, B]].

This is useful for dodgy XML data where the type of a value is not well defined - it might sometimes be an int, sometimes a boolean, for example:

"<root><either>123</either><either>true</either></root>".evalXPath[List[Either[Int, Boolean]]](xp"//either")
// res1: kantan.xpath.package.XPathResult[List[Either[Int, Boolean]]] = Right(
//   value = List(Left(value = 123), Right(value = true))
// )

Option

For any type A that has a NodeDecoder, there exists a NodeDecoder[Option[A]].

This is useful for XML where some nodes or attributes are optional. For example:

"<root><opt/></root>".evalXPath[Option[Int]](xp"//opt/@value")
// res2: kantan.xpath.package.XPathResult[Option[Int]] = Right(value = None)

XmlSource

The following types have an instance of XmlSource out of the box:


Other tutorials: