Richard Searle's Blog

Thoughts about software

Scala XMLLoader as ContentHandler

Posted by eggsearle on August 29, 2010

Scala makes it very easy to handle XML but does not provide any means to interact with the standard Java XML tooling. XML can only be created using literals or parsing the string representation.

The internal implementation of XML.load uses a ContentHandler. Exposing that ContentHandler would allow Scala XML to be created from a SAX pipeline, which is half of what is required for full integration

The following class provides the necessary implementation

import scala.xml.factory.XMLLoader
import scala.xml._
import org.xml.sax._
import org.xml.sax.helpers.DefaultHandler

class Loader extends DefaultHandler  with   XMLLoader[Elem]{
   val newAdapter = adapter
   def value = newAdapter.rootElem.asInstanceOf[Elem]

   override def characters( ch:Array[Char],start:Int,length:Int) {
   override def endDocument() {
   override def endElement(uri:String,localName:String, qName:String){
   override def processingInstruction(target:String,  data:String){
   override def startDocument(){
     newAdapter.scopeStack push TopScope
   override def startElement(uri:String,localName:String, qName:String,atts:Attributes){

Illustrated by

import javax.xml.parsers._
import javax.xml.transform._
import javax.xml.transform.sax.SAXResult

val transformerFactory = TransformerFactory.newInstance
val xformer = transformerFactory.newTransformer
val xl = new Loader
xformer.transform(new StreamSource(new StringBufferInputStream("""<X><y/>fdgfd</X>""")), new SAXResult(xl))

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: