A Scala XML NodeBuffer example

Here's a short example of how to use the Scala XML NodeBuffer class:

scala> val x = new xml.NodeBuffer
x: scala.xml.NodeBuffer = ArrayBuffer()

scala> x += <li>apple</li>
res0: x.type = ArrayBuffer(<li>apple</li>)

scala> x += <li>banana</li>
res1: x.type = ArrayBuffer(<li>apple</li>, <li>banana</li>)

scala> val ul = <ul>{x}</ul>
ul: scala.xml.Elem = <ul><li>apple</li><li>banana</li></ul>

As you can see, I build up a little list of li tags, and then include those in a ul tag at the end.

As you can see from the REPL response, the XML NodeBuffer class is closely related to the ArrayBuffer class. The NodeBuffer class extends the ArrayBuffer class, as shown in the following source code:

class NodeBuffer extends scala.collection.mutable.ArrayBuffer[Node] {

  def &+(o: Any): NodeBuffer = {
    o match {
      case null | _: Unit | Text("") => // ignore
      case it: Iterator[_] => it foreach &+
      case n: Node => super.+=(n)
      case ns: Iterable[_] => this &+ ns.iterator
      case ns: Array[_] => this &+ ns.iterator
      case d => super.+=(new Atom(d))
    }
    this
  }
}

The link to the NodeBuffer class source code keeps changing, but you can find it by following this NodeBuffer Scaladoc link, and then clicking on the source link.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.