Return to Snippet

Revision: 48328
at June 29, 2011 01:21 by studioevoque


Initial Code
object XmlHelpers {
    val docBuilder =
        javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder()
}

class NodeExtras(n: Node) {
    def toJdkNode(doc: org.w3c.dom.Document): org.w3c.dom.Node =
        n match {
            case Elem(prefix, label, attributes, scope, children @ _*) =>
                // XXX: ns
                val r = doc.createElement(label)
                for (a <- attributes) {
                    r.setAttribute(a.key, a.value.text)
                }
                for (c <- children) {
                    r.appendChild(c.toJdkNode(doc))
                }
                r
            case Text(text) => doc.createTextNode(text)
            case Comment(comment) => doc.createComment(comment)
            // not sure
            case a: Atom[_] => doc.createTextNode(a.data.toString)
            // XXX: other types
            //case x => throw new Exception(x.getClass.getName)
        }
}

class ElemExtras(e: Elem) extends NodeExtras(e) {
    override def toJdkNode(doc: org.w3c.dom.Document) =
        super.toJdkNode(doc).asInstanceOf[org.w3c.dom.Element]
    
    def toJdkDoc = {
        val doc = XmlHelpers.docBuilder.newDocument()
        doc.appendChild(toJdkNode(doc))
        doc
    }
}

implicit def nodeExtras(n: Node) = new NodeExtras(n)
implicit def elemExtras(e: Elem) = new ElemExtras(e)

Initial URL
https://gist.github.com/167566

Initial Description

                                

Initial Title
Convert Scala XML to Java DOM

Initial Tags
DOM, xml

Initial Language
Scala