For using a 3rd party library, I need a w3c DOM Document. However, creating the xml nodes is easier in Scala. So I'm looking for a way for converting a scala xml element to w3c dom. Obviously, I can serialize to a string and parse it, but I'm looking for something more performant.
+3
A:
Here's a simple (no namespaces) version you can build on. Should give the idea. Just replace the doc.createFoo(...) calls with their equivalent doc.createFooNS(...) ones. Also, might need smarter handling of the attributes. But, this should work for simple tasks.
object ScalaDom {
import scala.xml._
import org.w3c.dom.{Document => JDocument, Node => JNode}
import javax.xml.parsers.DocumentBuilderFactory
def dom(n: Node): JDocument = {
val doc = DocumentBuilderFactory
.newInstance
.newDocumentBuilder
.getDOMImplementation
.createDocument(null, null, null)
def build(node: Node, parent: JNode): Unit = {
val jnode: JNode = node match {
case e: Elem => {
val jn = doc.createElement(e.label)
e.attributes foreach { a => jn.setAttribute(a.key, a.value.mkString) }
jn
}
case a: Atom[_] => doc.createTextNode(a.text)
case c: Comment => doc.createComment(c.commentText)
case er: EntityRef => doc.createEntityReference(er.entityName)
case pi: ProcInstr => doc.createProcessingInstruction(pi.target, pi.proctext)
}
parent.appendChild(jnode)
node.child.map { build(_, jnode) }
}
build(n, doc)
doc
}
}
Mitch Blevins
2010-01-05 08:57:02