2010-01-04 8 views
9

타사 라이브러리를 사용하려면 w3c DOM 문서가 필요합니다. 그러나 Scala에서는 xml 노드를 만드는 것이 더 쉽습니다. 그래서 스칼라 xml 요소를 w3c dom으로 변환하는 방법을 찾고 있습니다. 분명히, 나는 문자열로 직렬화하고 그것을 파싱 할 수 있지만, 나는 더 성능이 좋은 것을 찾고있다.스칼라의 XML에서 w3c DOM으로의 변환은 무엇입니까?

답변

6

다음은 빌드 할 수있는 간단한 네임 스페이스 버전입니다. 아이디어를 주어야합니다. doc.createFoo (...) 호출을 해당 doc.createFooNS (...) 호출로 바꿉니다. 또한 속성을 더 똑똑하게 처리해야 할 수도 있습니다. 그러나 이것은 간단한 작업을 위해 작동해야합니다.

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