Created
August 14, 2009 01:15
-
-
Save stepancheg/167566 to your computer and use it in GitHub Desktop.
How to convert Scala XML to JDK DOM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment