简体   繁体   中英

Any conversion from scala's XML to w3c DOM?

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.

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
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM