Skip to content
philcali edited this page Nov 21, 2011 · 5 revisions

This section covers converting a collection of LMXML nodes into something useful.

The library ships with two types of converters:

  1. XmlConvert
  2. Transform (a special converter covered in Templating)

Under the Hood

An LmxmlConvert[A] trait is a function object, where type A is the result of the conversion.

Take a look at the XmlConvert definition.

Here is an example of parsing lmxml from a file, using the Lmxml object.

import lmxml._

val xml = Lmxml.fromFile("test.lmxml")(XmlConvert)

println(xml)

Working with Composition

As mentioned earlier, LmxmlConvert objects are simply Scala functions underneath, and therefore, can compose.

As an example, I want to censor all TextNode's coming in, replacing them with REDACTED.

object Censor extends LmxmlConvert[Seq[ParsedNode]] {
  def censor(node: ParsedNode) = n match {
    case t: TextNode => TextNode("REDACTED", children = apply(cs))
    case l: LmxmlNode => l.copy(children = apply(cs))
  }

  def apply(nodes: Seq[ParsedNode]): Seq[ParsedNode] = nodes match {
    case n :: ns => censor(n) :: apply(ns)
    case Nil => Nil
  }
}

val contents = """
lmxml
  has "many"
  great "features"
"""

val result = Lmxml.convert(contents)(Censor andThen XmlConvert)

println(result)

/*
<lmxml>
  <has>REDACTED</has>
  <great>REDACTED</great>
</lmxml>
*/

Clone this wiki locally