Posted By

studioevoque on 06/29/11


Tagged

DOM xml


Versions (?)

Convert Scala XML to Java DOM


 / Published in: Scala
 

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

  1. object XmlHelpers {
  2. val docBuilder =
  3. javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder()
  4. }
  5.  
  6. class NodeExtras(n: Node) {
  7. def toJdkNode(doc: org.w3c.dom.Document): org.w3c.dom.Node =
  8. n match {
  9. case Elem(prefix, label, attributes, scope, children @ _*) =>
  10. // XXX: ns
  11. val r = doc.createElement(label)
  12. for (a <- attributes) {
  13. r.setAttribute(a.key, a.value.text)
  14. }
  15. for (c <- children) {
  16. r.appendChild(c.toJdkNode(doc))
  17. }
  18. r
  19. case Text(text) => doc.createTextNode(text)
  20. case Comment(comment) => doc.createComment(comment)
  21. // not sure
  22. case a: Atom[_] => doc.createTextNode(a.data.toString)
  23. // XXX: other types
  24. //case x => throw new Exception(x.getClass.getName)
  25. }
  26. }
  27.  
  28. class ElemExtras(e: Elem) extends NodeExtras(e) {
  29. override def toJdkNode(doc: org.w3c.dom.Document) =
  30. super.toJdkNode(doc).asInstanceOf[org.w3c.dom.Element]
  31.  
  32. def toJdkDoc = {
  33. val doc = XmlHelpers.docBuilder.newDocument()
  34. doc.appendChild(toJdkNode(doc))
  35. doc
  36. }
  37. }
  38.  
  39. implicit def nodeExtras(n: Node) = new NodeExtras(n)
  40. implicit def elemExtras(e: Elem) = new ElemExtras(e)

Report this snippet  

You need to login to post a comment.