Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any conversion from scala's XML to w3c DOM?

Tags:

dom

xml

scala

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.

like image 234
IttayD Avatar asked Jan 04 '10 22:01

IttayD


1 Answers

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
  }
}
like image 81
Mitch Blevins Avatar answered Sep 19 '22 02:09

Mitch Blevins